python - 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++ 类型。关于我可能做错了什么的任何提示?
解决方案
推荐阅读
- formatting - 将交替行颜色添加到 SSRS 报告上的组
- apache-calcite - 如何利用方解石服务器
- java - 可以用我自己的对象来做到这一点(整数广告 = 8;和整数广告 = 8;)
- android - Windows 10,在 Qt Creator 中开发 Android 项目
- html - 如何仅使用 html 和 css 将两个按钮放在同一行?
- amazon-web-services - 如何通过 Amazon Elastic Beanstalk 发布 MVC Web 应用程序,使其不会删除 App_data 目录的任何内容?
- javascript - 这是否仍然可以关闭未由 javascript 打开的 chrome/firefox 选项卡
- c++ - std::string 是否保证不会自发归还内存?
- javascript - HTML 正则表达式与 JS 正则表达式相同吗?
- r - 考虑到R中的纬度和经度值,如何计算两个不同变量的平均值?