Can I use generated swig code to convert C++ object to PyObject?

Question:

I’m working on embedding python into my C++ program using swig. At the moment I have a object written in C++ which I want to pass to a python function. I’ve created the swig interface to wrap the class.

What I’m trying to do is take this C++ object which I’ve created and pass it to a python function with the ability to use it like I would in C++. Is it possible for me to use code generate by swig to do this? If not how can I approach this?

Asked By: Nexus

||

Answers:

You can use PyObject_CallMethod to pass a newly created object back to python. Assuming ModuleName.object is a python object with a method called methodName that you want to pass a newly created C++ object to you want to roughly (from memory, I can’t test it right now) do this in C++:

int callPython() {
   PyObject* module = PyImport_ImportModule("ModuleName");
   if (!module)
      return 0;

   // Get an object to call method on from ModuleName
   PyObject* python_object = PyObject_CallMethod(module, "object", "O", module);
   if (!python_object) {
      PyErr_Print();
      Py_DecRef(module);
      return 0;
   }

   // SWIGTYPE_p_Foo should be the SWIGTYPE for your wrapped class and
   // SWIG_POINTER_NEW is a flag indicating ownership of the new object
   PyObject *instance = SWIG_NewPointerObj(SWIG_as_voidptr(new Foo()), SWIGTYPE_p_Foo, SWIG_POINTER_NEW);

   PyObject *result = PyObject_CallMethod(python_object, "methodName", "O", instance);
   // Do something with result?

   Py_DecRef(instance);
   Py_DecRef(result);  
   Py_DecRef(module);

   return 1;
}

I think I’ve got the reference counting right for this, but I’m not totally sure.

Answered By: Flexo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.