【问题标题】:Dealing with opaque pointers in pybind11处理pybind11中的不透明指针
【发布时间】:2018-06-01 10:31:31
【问题描述】:

我正在将一个用 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>());
}

【问题讨论】:

    标签: python c++ boost pybind11 opaque-pointers


    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-30
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      • 1970-01-01
      • 2013-07-12
      • 2011-07-15
      • 2011-02-12
      相关资源
      最近更新 更多