Skip to content Skip to sidebar Skip to footer

Can I Use Generated Swig Code To Convert C++ Object To Pyobject?

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 interf

Solution 1:

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++:

intcallPython(){
   PyObject* module = PyImport_ImportModule("ModuleName");
   if (!module)
      return0;

   // 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);
      return0;
   }

   // 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(newFoo()), 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);

   return1;
}

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

Post a Comment for "Can I Use Generated Swig Code To Convert C++ Object To Pyobject?"