0

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*?

3 Answers 3

0

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

check it out

heres the documentation on functions

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.