我可以使用生成的 swig 代码将 C++ 对象转换为 PyObject 吗?

编程入门 行业动态 更新时间:2024-10-08 03:44:30
本文介绍了我可以使用生成的 swig 代码将 C++ 对象转换为 PyObject 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用 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 吗?

本文发布于:2023-11-02 07:06:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1551697.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可以使用   转换为   对象   代码   PyObject

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!