【发布时间】:2011-02-12 00:45:26
【问题描述】:
2 月 12 日编辑
我最近在使用 SWIG 生成的一些 C++ 类的 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?
【问题讨论】:
-
如果我的回答解决了您的问题,或者您找到了什么解决方案,请告诉我——这是一个有趣的问题!
-
遗憾的是,结论是“接受它”。没有好的解决方案出现 =(
标签: c++ python swig lifetime temporary-objects