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

放肆的年华 提交于 2019-12-23 18:32:48

问题


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?


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

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.



来源:https://stackoverflow.com/questions/5849012/can-i-use-generated-swig-code-to-convert-c-object-to-pyobject

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!