Dealing with opaque pointers in pybind11

795 Views Asked by At

I am moving a Python module written in C++ from Boost.Python to Pybind11. My C++ code relies on a C library that has opaque pointers. With Boost.Python, I used the documentation here to deal with these opaque pointers: https://www.boost.org/doc/libs/1_66_0/libs/python/doc/html/reference/to_from_python_type_conversion/boost_python_opaque_pointer_conv.html

I can't find the equivalent code for Pybind11. For reference, here is a C header that I want to expose to Python using Pybind11:

typedef struct mytruct* mystruct_t;

void myfunction1(mystruct_t x);

mystruct_t myfunction2();

This can be exposed with Boost.Python as follows:

BOOST_PYTHON_OPAQUE_SPECIALIZED_TYPE_ID(mystruct)

namespace bpl = boost::python;

BOOST_PYTHON_MODULE(mymodule) {
  bpl::opaque<mystruct>();
  bpl::def("f1", &myfunction1);
  bpl::def("f2", &myfunction2, bpl::return_value_policy<bpl::return_opaque_pointer>());
}
1

There are 1 best solutions below

0
On

If your goal is to simply permit passing pointers of a C++ object to Python without exposing information, you should just be able to register the class:

PYBIND_MODULE(mymodule, m) {
  py::class_<mystruct>(m, "mystruct");
  m.def("f1", &myfunction1);
  m.def("f2", &myfunction2);
}

If you wish to avoid conflict with other pybind11 modules that might declare types on this third-party type, consider using py::module_local():

https://pybind11.readthedocs.io/en/stable/advanced/classes.html#module-local-class-bindings