如何使用 boost::p ython 从 Python 类型中提取包装的C++类型

How can I extract a wrapped C++ type from a Python type using boost::python?

本文关键字:类型 提取 包装 C++ boost 何使用 ython Python      更新时间:2023-10-16

我已经使用 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)添加到我的主项目中并重新构建。