2月12日编辑的
我最近刚刚想出了一个奇怪的崩溃,对一些C++类使用一些SWIG生成的Python包装器。似乎SWIG和Python的组合有点急于清理临时值。如此迫切,事实上,它们在还在使用的时候就被清理掉了。一个显著压缩的版本如下所示:
/* Example.hpp */
struct Foo {
int value;
~Foo();
};
struct Bar {
Foo theFoo;
Bar();
};
/* Example.cpp */
#include "Example.hpp"
Bar::Bar() {theFoo.value=1;}
Foo::~Foo() {value=0;}
/* Example.i */
%module Example
%{
#include "Example.hpp"
%}
%include "Example.hpp"
我在.i文件上运行SWIG (1.3.37),然后在Python中,有:
Python 2.4.3 (#1, Sept 17 2008, 16:07:08)
[GCC 4.1.2 20071124 (Red Hat 4.1.2-41)] on linux2
Type "help", "copyright", "credits", or "license" for more information.
>>> from Example import Bar
>>> b=Bar()
>>> print b.theFoo.value # expect '1', since Bar's constructor sets this
1
>>> print Bar().theFoo.value # expect '1', since we're still using the Foo object
26403424
似乎在第二种情况下,临时Bar
对象在我们读取theFoo
的value
字段之前就被销毁了。在gdb中到处追逐东西,这显然就是发生的事情。所以当我们从Bar().theFoo
读取.value
时,C++已经销毁(并被其他堆分配覆盖) .theFoo
。在我的实际情况中,这导致了一个段错误。
有没有什么SWIG指令或技巧可以添加到我的Example.i
文件中,让Bar().theFoo.value
在这里返回1
?
https://stackoverflow.com/questions/4975509
复制相似问题