简体   繁体   English

在结构内分配数组的SWIG内存问题

[英]SWIG memory issue of allocating array inside a struct

Suppose I have a C struct like this 假设我有一个这样的C结构

struct foo {
    int sz;
    struct bar **arr;
};

In my SWIG file, I use "carrays.i" to give me control of the array inside this struct. 在我的SWIG文件中,我使用“ carrays.i”来控制此结构中的数组。 Here I use 在这里我用

%module mdl
%include "carrays.i"
%array_functions(struct bar*, barArray)

Then I allocate memory for this array in python. 然后我在python中为此数组分配内存。

a = mdl.foo()
a.arr = mdl.new_barArray(sz)

My question is, should I free the memory of the allocated array by calling 我的问题是,是否应该通过调用释放已分配数组的内存

mdl.delete_barArray(a.arr)

before I exit the current function, or SWIG will automatically do this for me so I don't need to worry about it? 在退出当前功能之前,否则SWIG会自动为我执行此操作,因此我不必为此担心吗?

You have to call delete when the array is no longer needed. 当不再需要该数组时,必须调用delete。 If you don't do it before the foo object reference count goes to zero and is destroyed, you have a memory leak. 如果在foo对象引用计数变为零并销毁之前不这样做,则可能会发生内存泄漏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM