How to marshall data structures from C/C++ into python and back

I have a program that is written in C++ and can be extended with extensions that are written in python using python's C api, basically there is python interpreter in the program which can load python modules that contains some hooks to various events.

I can pass simple data types from C to python, such as string or integer. I can do the same the other way, I can call internal C++ api's I created from the python modules. What I can't do, however is to marshall more complex data types, such as classes. For example I have this thing:

class X
{
    int a;
    int b;
};

I could call some python hook that would look like this:

def some_hook(a, b):
  print(str(a + b))

but I would rather do

def some_hook(x):
  print(str(x.a + x.b))

I know how to call a python function from C using PyObject_CallObject and how to give it some simple python vars as parameters (like integer or string). But I have no idea how to construct python classes from within C/C++, fill them up with data, and then pass them as parameters to PyObject_CallObject .

My idea was to create some proxy classes like in SWIG (swig.org) that I would fill up with data from C++ class and then back. I created some .py file that contains the declaration of these classes, but still, I have no idea how would I instantiate them from within C/C++ and fill up? Neither how I would do it the other way - turn PyObject into C/C++ class?

In a nutshell: I want to be able to turn C++ class into a python class, call a python function with that class as a parameter, and then call some other function from python with this class that would be just a C++ API that would turn the python class into C++.

Some background reading on how to call python from C: http://docs.python.org/3/extending/embedding.html

Source code of my app C++ that loads and uses python extensions: https://github.com/huggle/huggle3-qt-lx/blob/master/huggle/pythonengine.cpp

链接地址: http://www.djcxy.com/p/87904.html

上一篇: C ++数组在内存中的存储位置

下一篇: 如何将来自C / C ++的数据结构编组成python并返回