简体   繁体   中英

Pass an object from python script to c++

I have a simple c++ code which calls a python script. I was able to return an object from the python script to the c++ code, the problem now is that I can't figure out how to read that object in my c++.

relevant piece of python script

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

relevant 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();

I would very much appreciate an answer using the default python API (using python.h) not any other library

It turned out to be a very simple line of code shown here , all what I needed to do was to call PyObject_GetAttrString with the pyObject as the first argument and the name of the attribute I needed as the second.

In the following piece of code I check whether it exists or not then I print it.

PyObject_HasAttrString(methodcall, "msg") ? 
    printf(PyString_AsString(PyObject_GetAttrString(methodcall, "msg"))) :
    printf("ERROR\n");`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM