|
core-adapters 0.1.3
Third-party adapters for snicholls-core: nanobind helpers, nlohmann/json hooks, the snicholls_core Python package
|
bytes, bytearray, memoryview and str as zero-copy C++ views, and C++ bytes back as Python bytes.
More...
#include <nanobind/nanobind.h>#include <cstddef>#include <span>#include <string_view>#include <utility>Go to the source code of this file.
Classes | |
| class | snicholls::python::byte_view |
| A read-only view of a Python bytes-like object's contiguous buffer. More... | |
| class | snicholls::python::mutable_byte_view |
| A writable view of a Python object's contiguous buffer. More... | |
| class | snicholls::python::text_view |
A view of a str's UTF-8, or of a bytes-like buffer taken as UTF-8. More... | |
Functions | |
| ::nanobind::bytes | snicholls::python::to_bytes (std::span< const std::byte > b) |
A new Python bytes holding a copy of b. | |
| ::nanobind::bytes | snicholls::python::to_bytes (std::string_view s) |
A new Python bytes holding a copy of s. | |
bytes, bytearray, memoryview and str as zero-copy C++ views, and C++ bytes back as Python bytes.
std::span<const std::byte> and text as std::string_view. These argument types give a binding exactly that, with no copy, from whatever a Python caller has:| C++ argument | accepts | gives |
|---|---|---|
snicholls::python::byte_view | bytes, bytearray, memoryview, array.array, a C-contiguous NumPy array - anything with a contiguous buffer | std::span<const std::byte> |
snicholls::python::mutable_byte_view | a writable contiguous buffer (bytearray, writable memoryview, NumPy) | std::span<std::byte> |
snicholls::python::text_view | str (its UTF-8), and the bytes-like types above (taken as UTF-8 as they are) | std::string_view |
str is deliberately not a byte_view: text has no bytes until an encoding is chosen, so a caller writes s.encode(). Back to Python, to_bytes(span) / to_bytes(string_view) copy into a new bytes; a std::string or std::string_view result is a str as usual (<nanobind/stl/string.h>).
reflect/string_access.hpp (as_bytes_view) on the C++ side; nanobind's string casters.str) for their own lifetime, so the memory stays valid and, for a bytearray, its size stays fixed while a view exists (Python raises BufferError on a resize).TypeError); a read-only buffer fails for mutable_byte_view. to_bytes throws std::bad_alloc (MemoryError).to_bytes copies once.scripts/demos/bytes_demo.sh.snicholls::core_nanobind. The buffer protocol is in the stable ABI from Python 3.11, so these work in abi3 modules.const& only in the function signature; never store one beyond the call.text_view of bytes is not checked for valid UTF-8, exactly as std::string_view would not be.Definition in file bytes.hpp.