如何使用 boost::p ython 从 Python 类型中提取包装的C++类型
How can I extract a wrapped C++ type from a Python type using boost::python?
我已经使用 Py++ 包装了一个C++类,在 Python 中一切正常。我可以实例化 c++ 类、调用方法等。
我现在正在尝试将一些 Python 嵌入到C++应用程序中。在大多数情况下,这也工作正常。我可以在 Python 模块上调用函数,获取返回值等。
我调用的 python 代码返回我包装的类之一:
import _myextension as myext
def run_script(arg):
my_cpp_class = myext.MyClass()
return my_cpp_class
我从C++调用这个函数,如下所示:
// ... excluding error checking, ref counting, etc. for brevity ...
PyObject *pModule, *pFunc, *pArgs, *pReturnValue;
Py_Initialize();
pModule = PyImport_Import(PyString_FromString("cpp_interface"));
pFunc = PyObject_GetAttrString(pModule, "run_script");
pArgs = PyTuple_New(1); PyTuple_SetItem(pArgs, 0, PyString_FromString("an arg"));
pReturnValue = PyObject_CallObject(pFunc, pArgs);
bp::extract< MyClass& > extractor(pReturnValue); // PROBLEM IS HERE
if (extractor.check()) { // This check is always false
MyClass& cls = extractor();
}
问题是提取器从未实际提取/转换 PyObject* 到 MyClass(即 extractor.check() 总是假的)。
根据文档,这是提取包装C++类的正确方法。
我尝试从 Python 函数返回基本数据类型(ints/floats/dicts),并且所有这些都被正确提取。
我错过了什么吗?有没有其他方法可以获取数据并投射到 MyClass?
我发现了错误。我没有在我的主可执行文件中链接我的绑定,因为这些绑定是在仅创建 python 扩展的单独项目中编译的。
我假设通过使用pModule = PyImport_Import(PyString_FromString("cpp_interface"));
加载扩展,绑定也会被加载,但事实并非如此。
为了解决这个问题,我只是将包含我的 boost::p ython 绑定的文件(对我来说,只是包装器.cpp)添加到我的主项目中并重新构建。
相关文章:
- C++从通用引用中提取实际类型
- Clang 工具,用于提取给定 lambda 类型的 lambda 主体
- 将不同类型的模板参数包提取到双精度向量中会产生警告
- 在C++如何从数组中提取成员并返回成员类型的数组?
- 从 Any 包中提取和匹配 protobuf 消息类型名的首选方法
- 从具有部分专用化的boost:hana::set中提取类型失败
- 如何提取模板参数中传递的类型
- 从 std::set 中提取仅移动类型
- 需要根据读取的数据类型将ifstream提取到单独的数组中
- 如何定义变体<x,y,z>提取模板参数的子类型
- 从传递给模板函数的内部类实例中提取外部类类型
- 防止为字符串流提取运算符不支持的类型实例化模板类 (>>)
- C++ HDF5 提取复合数据类型的一个成员
- 从参数包中提取成员类型
- 如何使用 boost::p ython 从 Python 类型中提取包装的C++类型
- 从字符串中提取不同的数据类型变量
- 提取模板类中的类型以用于其他模板
- 制作解析器以提取函数名称、参数、返回类型
- 提取函数指针参数和返回类型
- 将函数参数类型提取为参数包