[英]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.