![](/img/trans.png)
[英]How to wrap a c++ class to python so that I can access its members' public methods (the member is an object pointer) using pybind11
[英]I can create my C++ object in Python, but can't access methods
抱歉,这里有很多东西,但是我真的认为所有这些信息都与我要问的问题有关。
因此,我使用SWIG,编译等方法包装了C ++类,并在python脚本中创建了类的实例,然后尝试在该类上调用方法。 注意我说“尝试”呼叫。 该方法的调用失败。 有关实现和“失败”的详细信息如下。
首先,我要使用Windows应用程序构建Python3.4解释器,并按如下方式调用python脚本:
Py_Initialize();
/* Some code here to set up python paths. */
.....
PyObject *pName = PyUnicode_FromString("hello");
if(pName == NULL)
{
Py_Finalize();
return false;
}
PyObject* pModule = PyImport_Import(pName);
if(pModule == NULL)
{
Py_Finalize();
return false;
}
/* "go" is the name of the function in my python script that I want to call. */
PyObject *pFunc = PyObject_GetAttrString(pModule, "go");
if(pFunc == NULL)
{
Py_Finalize();
return false;
}
PyObject *pArgs = PyTuple_New(0);
PyObject *pValue = PyObject_CallObject(pFunc, pArgs);
if(pValue == NULL)
{
Py_Finalize();
return false;
}
Py_Finalize();
return true;
===================
这是我的课程结构:
class BoganDocument
{
private:
BoganMetadataSet myMetadata;
public:
// Constructor
BoganDocument();
// Destructor
virtual ~BoganDocument();
// Useful methods.
wstring getMetadataValue(wstring metadata_name);
}
===================
这是我的Python脚本(名为“ hello.py”)。
import BoganDocument
def go():
print("I'm in go()")
d = BoganDocument.BoganDocument()
print("I made a document")
ts = d.getMetadataValue("CreationTimestamp");
print("The creation timestamp is " + ts)
=====================
控制台屏幕上的输出如下所示:
trying C:\Program Files (x86)\MyApp\Python\swig_runtime_data4_d.pyd
trying C:\Program Files (x86)\MyApp\Python\swig_runtime_data4.py
trying C:\Program Files (x86)\MyApp\Python\swig_runtime_data4.pyw
trying C:\Program Files (x86)\MyApp\Python\swig_runtime_data4.pyc
trying c:\MyApp\Workplace\swig_runtime_data4_d.pyd
trying c:\MyApp\Workplace\swig_runtime_data4.py
trying c:\MyApp\Workplace\swig_runtime_data4.pyw
trying c:\MyApp\Workplace\swig_runtime_data4.pyc
import 'BoganDocument' # <_frozen_importlib.SourceFileLoader object at 0x10D2E3F0>
import 'hello' # <_frozen_importlib.SourceFileLoader object at 0x10D2E1C0>
I'm in go()
I made a document
===================
请注意,我已将PYTHONVERBOSE设置为11以获取尽可能多的诊断信息。 并请注意,所有消息均在“ print(“我制作了文档”)“之后停止。 没有语法错误,什么都没有。 “ PyObject * pValue = PyObject_CallObject(pFunc,pArgs);”之后的pValue值。 一片空白。
现在,众所周知,在“ d = BoganDocument.BoganDocument()”处对构造函数的调用是有效的,因为我已经在BoganDocument构造函数中设置了一个断点并单步执行。
我还在BoganDocument的getMetadataValue方法中设置了一个断点,但从未到达那里。 还有一个谜。
毫无疑问,我有一个错误,但是我没有任何线索。
您是否进入了针对getMetadataValue
的SWIG 包装器 ? 在Python中执行d.getMetadataValue()
,将调用C ++包装器,然后C ++包装器在适当的C ++实例上调用Bogan::getMetadataValue
。 由于您从未接触过C ++实例的getMetadataValue
,因此SWIG包装程序可能发现该调用是非法的(SWIG通常不会默默地忽略问题,但我不知道还有什么建议)。 由于您使用的是宽字符串,因此请确保包含std_wstring.i
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.