pybind / pybind11

Seamless operability between C++11 and Python
https://pybind11.readthedocs.io/
Other
15.6k stars 2.09k forks source link

Eigen Matrix + buffer_protocol #1636

Open asadchev opened 5 years ago

asadchev commented 5 years ago

What is correct way to give Eigen matrix buffer protocol?

Doing this

py::class_<Eigen::MatrixXd>(m, "MatrixXd", pybind11::buffer_protocol())
  .def_buffer([](Matrix<double> &m) { return py::buffer_info { ... }});

will cause segfault if pybind11/eigen.his included as in def_buffer

install_buffer_funcs([](PyObject *obj, void *ptr) -> buffer_info* {
            detail::make_caster<type> caster;
            if (!caster.load(obj, false)) {
              return nullptr;
            }

null pointer is returned

EricCousineau-TRI commented 5 years ago

If I understand correctly, you'll want to use pybind11/eigen.h's ability to do pass-by-reference: https://pybind11.readthedocs.io/en/stable/advanced/cast/eigen.html#pass-by-reference

Then you can do stuff like what's in the unittests: https://github.com/pybind/pybind11/blob/e2b884c33bcde70b2ea562ffa52dd7ebee276d50/tests/test_eigen.cpp#L128 https://github.com/pybind/pybind11/blob/e2b884c33bcde70b2ea562ffa52dd7ebee276d50/tests/test_eigen.py#L489

If you're not looking to expose type_casters for Eigen::Map<>-based types, can I ask what you are looking to do?