Passing a C++ object to Python Passing a C++ object to Python python python

Passing a C++ object to Python


This is a partial answer to my own question. I'm saying partial, because I do believe there is a better way.

Building on this post http://swig.10945.n7.nabble.com/Pass-a-Swig-wrapped-C-class-to-embedded-Python-code-td8812.htmlI generated the swig runtime header, as described here, section 15.4: http://www.swig.org/Doc2.0/Modules.html#Modules_external_run_time

Including the generated header in the C++ code above, allow the following code to be written:

    PyObject* pObj = SWIG_NewPointerObj((void*)&obj, SWIG_TypeQuery("_p_MyClass"),  0 ); 

This code is using information from the Swig python wrap source files, namely the "swig" name of the type MyClass, i.e. _p_MyClass.

With the above PyObject* as an argument to the PyObject_CallObject function, the python execute() function in the code above executes fine, and the Python code, using the generated python module, do have proper access to the MyClass objects internal data. This is great.

Although the above code illustrate how to pass, and retrieve data between C++ and Python in a quite simple fashion, its not ideal, in my opinion.

The usage of the swig header file in the C++ code is really not that pretty, and in addition, it requires a user to "manually" look into swig generated wrapper code in order to find the "_p_MyClass" code.

There must be a better way!? Perhaps something should be added to the swig interface file in order to get this looking nicer?


Unfortunatle it does not work in my case.I get nullptr exception inside SWIG_TypeQuery("_p_MyClass") macros.

Could you please share more details how to do such passing?

  1. I have MyClass library
  2. Based on this library I created module using swig
  3. Next I created swigpyrun.h file using -external-runtime
  4. I included this file into my main.cpp, and SWIG_TypeQuery("_p_MyClass") gives an error

I even tried to add definitions like SWIG_TYPE_TABLE, but it did not help.

BTW I am using MSVS compilter


PyObject *pValue;pValue = PyObject_CallMethod(pInstance, "add","(i)",x);if (pValue)    Py_DECREF(pValue);else    PyErr_Print();