这应该是一个简单的程序,但我已经有几天没有去做了。在
我的情况如下:
我用SWIG包裹了一个相对简单的C++接口,所以我可以用Python来使用它。然而,由于其中一个方法返回了一个自定义结构,其定义如下:struct DashNetMsg {
uint64_t timestamp;
char type[64];
char message[1024];
};
以下是我的SWIG接口文件:
^{pr2}$“DashboardClient.h”和仪表板客户端.cpp声明并定义类“DashboardClient”及其方法,我正在包装这些方法“DashNetMsg.h”是一个头文件,它实际上只包含上面的结构定义。以下是仪表盘客户端.Recv方法,来自DashboadClient.cpp公司名称:
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.
首先,DashNetMsg显然定义了一个名为“type”的属性。第二,内存泄漏是怎么回事?根据SWIG的说法:
SWIG creates default constructor and destructor functions if none are defined in the interface.
(http://www.swig.org/Doc2.0/SWIG.html,第5.5节)
这不意味着它应该为这个包装类型创建一个析构函数吗? 另外,为什么我不能访问我的结构的属性?在
无效的解决方案
我最好的猜测是,SWIG出于某种原因实际上并没有包装DashNetMsg结构,而是将其视为一个不透明的指针。因为SWIG似乎表明释放这些指针指向的内容必须手动完成,所以我想它也可以解释内存泄漏的原因。但是,即使是这样,我也不明白SWIG为什么不包装这个结构。在
我读到hereswig必须有声明为C-style的结构才能识别它们。我就这样尝试了:
typedef struct DashNetMsg {
uint64_t timestamp;
char type[64];
char message[1024];
} DashNetMsg;
结果与上述结果完全相同。在
用SWIG按值返回
struct
s是很棘手的。From their documentation:相关问题 更多 >
编程相关推荐