我已经使用 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?