首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >SWIG的Python包装器中临时对象的生命周期(?)

SWIG的Python包装器中临时对象的生命周期(?)
EN

Stack Overflow用户
提问于 2011-02-12 08:45:27
回答 1查看 2.1K关注 0票数 8

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对象在我们读取theFoovalue字段之前就被销毁了。在gdb中到处追逐东西,这显然就是发生的事情。所以当我们从Bar().theFoo读取.value时,C++已经销毁(并被其他堆分配覆盖) .theFoo。在我的实际情况中,这导致了一个段错误。

有没有什么SWIG指令或技巧可以添加到我的Example.i文件中,让Bar().theFoo.value在这里返回1

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4975509

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档