![](/img/trans.png)
[英]Python: pass c++ object to a script, then invoke extending c++ function from script
[英]Pass an object from python script to c++
我有一个简单的c ++代码,它调用python脚本。 我能够将对象从python脚本返回到c ++代码,现在的问题是我不知道如何在c ++中读取该对象。
相关的python脚本
class obj():
def __init__(self):
self.msg = "hello"
self.i = 8
class Test():
def __init__(self, c):
self.c = c
def finalize(self):
t = obj()
print t.msg, t.i
return t
相关的c ++
Py_Initialize();
PyObject *import, *attr, *instance, *methodcall, *arg, *tuple;
PySys_SetPath("./py/");
import = PyImport_ImportModule("script");
attr = PyObject_GetAttrString(import, "Test");
arg = PyString_FromString("arg from first");
tuple = PyTuple_Pack(1, arg);
instance = PyInstance_New(attr, tuple, NULL);
methodcall = PyObject_CallMethod(instance, "finalize", NULL);
Py_Finalize();
我非常感谢使用默认python API(使用python.h)而不是其他任何库的答案
原来这是一个非常简单的显示代码行这里 ,所有我需要做的是调用PyObject_GetAttrString
用的PyObject作为第一个参数,我需要为第二属性的名称。
在下面的代码中,我检查它是否存在,然后打印出来。
PyObject_HasAttrString(methodcall, "msg") ?
printf(PyString_AsString(PyObject_GetAttrString(methodcall, "msg"))) :
printf("ERROR\n");`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.