C++ 包装和使用返回SWIG结构的函数时出现问题(python)
这应该是一个简单的程序,但它仍然逃避了我几天了 我的情况如下:C++ 包装和使用返回SWIG结构的函数时出现问题(python),c++,python,pointers,struct,swig,C++,Python,Pointers,Struct,Swig,这应该是一个简单的程序,但它仍然逃避了我几天了 我的情况如下: struct DashNetMsg { uint64_t timestamp; char type[64]; char message[1024]; }; 我用SWIG包裹了一个相对简单的C++接口,所以我可以用Python来使用它。然而,由于其中一个方法返回一个自定义结构,其定义如下,因此问题变得复杂: struct DashNetMsg { uint64_t timestamp; char ty
struct DashNetMsg {
uint64_t timestamp;
char type[64];
char message[1024];
};
我用SWIG包裹了一个相对简单的C++接口,所以我可以用Python来使用它。然而,由于其中一个方法返回一个自定义结构,其定义如下,因此问题变得复杂:
struct DashNetMsg {
uint64_t timestamp;
char type[64];
char message[1024];
};
以下是我的SWIG接口文件,用于完成此操作:
%module DashboardClient
%{
#include "aos/atom_code/dashboard/DashNetMsg.h"
#include "DashboardClient.h"
%}
%import "aos/atom_code/dashboard/DashNetMsg.h"
%include "DashboardClient.h"
%ignore Recv(DashNetMsg *);
“DashboardClient.h”和“DashboardClient.cpp”声明并定义了我正在包装的类“DashboardClient”及其方法。“DashNetMsg.h”是一个头文件,它实际上只包含上面的结构定义。以下是DashboadClient.cpp中DashboardClient.Recv方法的定义:
DashNetMsg DashboardClient::Recv() {
DashNetMsg ret;
if (Recv(&ret)) {
// Indicate a null message
strcpy(ret.type, "NullMessage");
}
return ret;
}
当我编译并将其加载到python中时,会出现两个有趣且(我认为)相互关联的问题:
Python 3.1.3 (r313:86834, Nov 28 2010, 10:01:07)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import DashboardClient
>>> d = DashboardClient.DashboardClient()
>>> m = d.Recv()
>>> m
<Swig Object of type 'DashNetMsg *' at 0x7f4d4fc2d3c0>
>>> m.type
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'SwigPyObject' object has no attribute 'type'
>>> exit()
swig/python detected a memory leak of type 'DashNetMsg *', no destructor found.
它的结果与上面的结果完全相同。使用SWIG按值返回
struct
s很棘手:
按值返回结构或类数据类型的C函数更难处理…SWIG只支持指针
SWIG分配一个新对象并返回对它的引用。当返回的对象不再使用时,由用户删除该对象。显然,如果您不知道隐式内存分配,并且不采取步骤释放结果,这将导致内存泄漏
因此,如果出现最坏的情况,我将在界面中回避这个问题。然而,我觉得这应该是可能的…@nneonneo如果SWIG只返回对新对象的引用,会发生什么情况。如何访问该对象?我可以将返回的引用保存在变量上并使用它吗?