在SWIG中传递向量元素时的自动内存管理

2024-10-04 11:34:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我想包装对象Foo的构造函数,它接受指向Bar的指针向量:

    Foo(std::vector<Bar*> const&); //!< Constructor

在我的接口文件中,我有:

%include "std_vector.i" 
%template (vector_bar_p) std::vector<Bar*>;
%include "foo.h"

以这样一种方式,我可以从Python中找到一个Foo,比如:

bar1, bar2 = Bar(), Bar()
foo = Foo([bar1,bar2]) 
<>问题是,当^ {CD3>}和^ {CD4>}被垃圾收集时,也删除了基础C++内存,而在{{CD5>}中的方法导致了分割错误。我可以用以下方法解决:

bar1.thisown = 0
bar2.thisown = 0

但是我想要一种在调用Foo的构造函数时自动设置thisown标志的方法,最好是通过接口文件中的类型映射。你知道吗


Tags: 文件对象方法fooincludebar向量指向
1条回答
网友
1楼 · 发布于 2024-10-04 11:34:28

这是不可能的。从SWIG 3.0 documentation

Given the tricky nature of C++ memory management, it is impossible for proxy classes to automatically handle every possible memory management problem. However, proxies do provide a mechanism for manual control that can be used (if necessary) to address some of the more tricky memory management problems.

如今,使用原始指针进行操作似乎也很可疑。我建议使用std::vector<std::shared_ptr<Bar>>vector<Bar>提供的有效副本构造函数Bar。你知道吗

相关问题 更多 >