3

我正在将用 C++ 编写的 Python 模块从 Boost.Python 移动到 Pybind11。我的 C++ 代码依赖于具有不透明指针的 C 库。对于 Boost.Python,我使用此处的文档来处理这些不透明的指针: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

我找不到 Pybind11 的等效代码。作为参考,这是我想使用 Pybind11 向 Python 公开的 C 标头:

typedef struct mytruct* mystruct_t;

void myfunction1(mystruct_t x);

mystruct_t myfunction2();

这可以通过 Boost.Python 公开,如下所示:

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>());
}
4

1 回答 1

1

如果您的目标是简单地允许将 C++ 对象的指针传递给 Python 而不会暴露信息,那么您应该能够注册该类:

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

如果您希望避免与pybind11可能在此第三方类型上声明类型的其他模块发生冲突,请考虑使用py::module_local()

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

于 2019-05-05T12:17:22.567 回答