SWIG - 使用 %newobject 的垃圾收集 [英] SWIG - Garbage Collection using %newobject
问题描述
在我的 C 代码中,我有以下结构:
In my C code, I have the following structure :
typedef struct my_structure{
char* str1;
char* str2;
}MyStruct;
还有一个返回 MyStruct 指针的函数:
And a function that returns a MyStruct pointer :
MyStruct* foo();
在foo里面,我已经为MyStruct、str1和str2分配了内存,如下:
Inside foo, I have allocated memory for MyStruct , str1 and str2, as follows:
MyStruct* obj = malloc(sizeof(MyStruct));
obj.str1 = malloc(256);
obj.str2 = malloc(256);
我想从 python、java、C# 和 PHP 调用 foo 并且我不想在这个过程中有任何内存泄漏.
I want to call foo from python, java, C# and PHP and I don't want to have any memory leak in this process.
我不确定是否写:
%newobject foo;
MyStruct* foo();
保证垃圾收集器将为结构和其中的字符串释放内存.
guarantees that the garbage collector will free memory for both the structure and the strings inside it.
我不想让调用者有义务为 str1 和 str2 显式释放内存,因为我正在寻找一种自动释放内存的方法.这可能吗?
I didn't want to obligate the caller to explicit free memory for str1 and str2 as I was looking for an automatic way of freeing memory. Is this possible?
在这种情况下,我必须使用newfree"类型映射吗?
Do I have to use "newfree" typemap in this case?
如果您能提供一个示例来展示实现此目的的最佳方法,我将不胜感激.
I would greatly appreciate if you could provide me an example showing the best way to accomplish this.
谢谢!
推荐答案
typemap(newfree)
立即释放返回的 %newobject
使用的内存,例如当 achar* 返回值转换为 Python 字符串,不再需要分配的对象.我认为您想要的是 %extend
SWIG 围绕您的 C 结构生成的类包装器以提供析构函数:
typemap(newfree)
frees the memory used by the returned %newobject
immediately, such as when a char* return value is converted into a Python string and the allocated object is no longer needed. I think what you want is %extend
the class wrapper that SWIG generates around your C structure to provide a destructor:
%newobject foo;
%extend MyStruct {
~MyStruct() {
free($self->str1);
free($self->str2);
}
}
如果这解决了您的问题,请发表评论.这是基于我自己对 SWIG 文档中的内容进行的实验,并在我生成的简单包装器中正常工作.
Please comment if this solves your issue. This is based on my own experimentation with what I could find in the SWIG documentation and worked correctly in the simple wrapper I generated.
这篇关于SWIG - 使用 %newobject 的垃圾收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!