[英]How can I extract a wrapped C++ type from a Python type using boost::python?
I've wrapped a C++ class using Py++ and everything is working great in Python. 我已经使用Py ++封装了C ++类,并且在Python中一切正常。 I can instantiate the c++ class, call methods, etc.
我可以实例化c ++类,调用方法等。
I'm now trying to embed some Python into a C++ application. 我现在正尝试将一些Python嵌入C ++应用程序中。 This is also working fine for the most-part.
在大多数情况下,这也可以正常工作。 I can call functions on a Python module, get return values, etc.
我可以在Python模块上调用函数,获取返回值等。
The python code I'm calling returns one of the classes that I wrapped: 我正在调用的python代码返回我包装的类之一:
import _myextension as myext
def run_script(arg):
my_cpp_class = myext.MyClass()
return my_cpp_class
I'm calling this function from C++ like this: 我从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();
}
The problem is the extractor never actually extracts/converts the PyObject* to MyClass (ie extractor.check() is always false). 问题是提取器实际上从未将PyObject *提取/转换为MyClass(即extractor.check()始终为false)。
According to the docs this is the correct way to extract a wrapped C++ class. 根据文档,这是提取包装的C ++类的正确方法。
I've tried returning basic data types (ints/floats/dicts) from the Python function and all of them are extracted properly. 我试过从Python函数返回基本数据类型(ints / floats / dicts),并且所有数据都已正确提取。
Is there something I'm missing? 有什么我想念的吗? Is there another way to get the data and cast to MyClass?
还有另一种获取数据并转换为MyClass的方法吗?
I found the error. 我发现了错误。 I wasn't linking my bindings in my main executable because the bindings were compiled in a separate project that created the python extension only.
我没有在我的主要可执行文件中链接我的绑定,因为这些绑定是在一个仅创建python扩展的单独项目中编译的。
I assumed that by loading the extension using pModule = PyImport_Import(PyString_FromString("cpp_interface"));
我假设通过使用
pModule = PyImport_Import(PyString_FromString("cpp_interface"));
加载扩展名pModule = PyImport_Import(PyString_FromString("cpp_interface"));
the bindings would be loaded as well, but this is not the case. 绑定也将被加载,但事实并非如此。
To fix the problem, I simply added the files that contain my boost::python bindings (for me, just wrapper.cpp) to my main project and re-built. 为了解决这个问题,我只是将包含boost :: python绑定的文件(对我来说只是wrapper.cpp)添加到我的主项目中,然后重新构建。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.