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
在这里?
最佳答案
第二次更新:
我们知道基本问题是 python 破坏了 Bar
立即地。当Bar
在python中实现,python的gc知道还有对theFoo
的引用,所以不会破坏它。但是当Bar
c++实现,python调用c++析构函数,自动销毁theFoo
连同 Bar.
所以显而易见的解决方案是防止 python 破坏 Bar
过早地。这是一个涉及子类化的稍微有点老套的解决方案 Bar
:
class PersistentBar(swigexample.Bar):
lastpbar = None
def __init__(self):
super(PersistentBar, self).__init__()
PersistentBar.lastpbar = self
这将保存对最后一个 Bar
的引用创建以便它不会立即被销毁。当一个新的 Bar
被创建,旧的被删除。 (我的旧版本很愚蠢;不需要为此覆盖 __del__
。)这是输出(在 cout << "deleting Foo "
的析构函数中有 Foo
):
>>> from test import persistentBar
>>> persistentBar().theFoo.value
1
>>> persistentBar().theFoo.value
deleting Foo 1
>>> persistentBar().theFoo.value
deleting Foo 1
我还是不喜欢这个。隔离装饰器中的“持久”行为可能会更好;我也试过了,它起作用了(如果你想看代码,请告诉我)。以某种方式告诉 python 处理销毁 theFoo
肯定会更好本身,但我不知道该怎么做。
第一次更新:
wrap 代码什么也没告诉我,所以我查看了 swigexample.py。那也一无所获。当我尝试复制 Bar
时,事情变得更清楚了在纯 python 中:
# pyfoobar.py
class Foo(object):
def __init__(self):
self.value = -1
class Bar(object):
def __init__(self):
self.theFoo = Foo()
self.theFoo.value = 1
def __del__(self):
self.theFoo.value = 0
现在我们从 pyfoobar 导入 Bar:
>>> from pyfoobar import Bar
>>> b = Bar()
>>> b.theFoo.value
1
>>> Bar().theFoo.value
0
此行为来自 Python!
原始答案:
似乎这里肯定有一些垃圾收集斗争...这是关于 SWIG Memory Management 的一些相关信息.基于此,看起来 %newobject 指令可能就是您要找的;但我尝试了几种变体,但无法让 python 控制 theFoo
:
>>> from swigexample import Bar
>>> b = Bar()
>>> b.theFoo.value
1
>>> b.theFoo.thisown
False
>>> Bar().theFoo.value
0
>>> Bar().theFoo.thisown
False
我开始怀疑这是故意的;上面链接中的这一行似乎与这里相关:
C is now holding a reference to the object---you probably don't want Python to destroy it.
但我不确定。我将查看 swigexample_wrap 代码,看看我是否可以确定何时 ~Bar
正在调用。
关于c++ - SWIG 的 Python 包装器中临时对象的生命周期(?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4975509/