首页 > 解决方案 > Pybind11:将自定义 python 类型转换为自定义 C++ ptr

问题描述

试图为 c++ 函数制作 python 绑定。函数采用路径和自定义类型 pT 的对象。

.def("myFunc", [](myClass &self, py::args args){
    std::string path;
    path = py::str(args[0]);

    mySmartPtr *cls = args[1].cast<mySmartPtr *>();
    return self.myFunc(path, *cls);
})

它编译得很好,在运行时给出错误: Unable to cast Python instance of type <pT> to C++ type 'std::shared_ptr<myClass>'

尝试以不同的方式进行投射: mySmartPtr &cls = py::cast<mySmartPtr &>(args[1]); 它给出了相同的错误。

和:

py::object obj = args[1];
std::dynamic_pointer_cast<mySmartPtr> (obj);

给出错误:

error: no matching function for call to 'dynamic_pointer_cast(pybind11::object&)'
note:   'pybind11::object' is not derived from 'const std::__shared_ptr<_Tp2, _Lp>'

遵循文档,尝试通过以下方式直接提取 PyObject: PyObject *cls = args[1].ptr(); 它在运行时崩溃并显示消息:“分段错误”。

这个 Python 类型 pT 完全可以转换成 c++ 类型。关于我可能做错了什么的任何提示?

标签: pythonc++pybind11

解决方案


推荐阅读