问题描述
我正在使用 swig 将 python 嵌入到我的 C++ 程序中.目前我有一个用 C++ 编写的对象,我想将其传递给 python 函数.我已经创建了 swig 接口来包装类.
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.
我想要做的是将我创建的这个 C++ 对象传递给一个 python 函数,该函数可以像在 C++ 中一样使用它.我是否可以使用 swig 生成的代码来执行此操作?如果不是,我该如何处理?
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?
推荐答案
您可以使用 PyObject_CallMethod 将新创建的对象传回给 python.假设 ModuleName.object
是一个 python 对象,它有一个名为 methodName
的方法,你想将一个新创建的 C++ 对象传递给你想要粗略的(从内存中,我不能立即测试)在 C++ 中执行此操作:
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.
这篇关于我可以使用生成的 swig 代码将 C++ 对象转换为 PyObject 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!