简体   繁体   中英

How to pass C++ classes as arguments when calling python functions from C++?

I am writing a C++ application that needs load a Python module, and calls functions in that module. The application needs to pass to the python function a C++ claseses as arguments. I managed to call python code from the C++ code, but I only manage to pass "primative" types as arguments.

I create wrappers/interfaces using SWIG, but I failed to find how to convert my C++ class from the application to PyObject* in order to pass it as argument to the python functions.

Do you know where I can find information about how to perform the casting from C++ to PyObject*?

Boost has a python interface library which might be helpful for you.

check it out

heres the documentation on functions

I still dont have a solution, I only have the following workaround: 1. I create a PyObject from the instance, and pass it to the python function. 2. The python code, uses a function in the library that was generated by SWIG, to convert the PyObject to the python version of the class.

implementation:

In C++ file

MyClass myObject;
...
PyObject *parameterForPython = PyCObject_FromVoidPtr(&myObject, NULL); // step 1
PyTuple_SetItem(pyArgs, 0, parameterForPython);
PyObject_CallObject(pythonFunctionObject, pyArgs);

In swig interface file (code for step 2) :

%inline %{
    MyClass *convertPyObjectToMyClass(PyObject * ptr) {
        return (MyClass *)PyCObject_AsVoidPtr(ptr)
    }
%}

In python module:

def myPythonFunction(ptr):
    myObject = cppmodule.convertPyObjectToMyClass(ptr) #step 2

Have you considered to use SWIG_NewPointerObj(ptr, type, flags) or SWIG_ConvertPtr(obj, pptr, type, flags) ?

You can have those declarations by running:

swig -python -external-runtime swig-python.h

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