You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
py::class_<Matrix>(m, "Matrix", py::buffer_protocol())
.def_buffer([](Matrix &m) -> py::buffer_info {
returnpy::buffer_info(m.raw, /* Pointer to buffer */sizeof(float), /* Size of one scalar */
py::format_descriptor<float>::format(), /* Python struct-style format descriptor */2, /* Number of dimensions */
{m.rows(), m.cols()}, /* Buffer dimensions */
{sizeof(float)*m.cols(), /* Strides (in bytes) for each index */sizeof(float) });
});
Everywhere else, we need return a pybind11::array or pybind11::array_t<T> for numpy
types and pybind11::buffer for more general buffer-enabled classes.
The 0-copy way of doing this is the following
// Get a pointer to the vector object (this is copy-free, since move-constructed)auto v = new std::vector<int>(some_func());
// pybind11 smart-pointer any hybrid with explicit deleterauto capsule = py::capsule(v, [](void *v) { deletereinterpret_cast<std::vector<int>*>(v); });
// Create an array from the raw data and capsule, where the capsule's lifetime is bound// to that of the array and in turn will (C++) delete the vector object.return py::array(v->size(), v->data(), capsule);
if we can live with a copy, this should be used to be less stressful on my sanity (no lifetime management madness)
auto v = some_func();
return py::array(v.size(), v.data());
As @halfflat say, the probe API is covered already and with that the main usecase. After trawling the Python
interface I could not find more, so I am closing this with the request to re-open, if I missed something.
The notes above can serve as reference on how to achieve numpy compatibility where needed.
see https://pybind11.readthedocs.io/en/stable/advanced/pycpp/numpy.html?highlight=numpy
Add
buffer_info
to all wrapped python objects returning lists (e.g. stdandard vector, list, array, deque)The text was updated successfully, but these errors were encountered: