SWIG - 使用 %newobject 进行垃圾收集

发布于 2024-10-09 19:47:32 字数 688 浏览 0 评论 0原文

在我的 C 代码中,我有以下结构:

typedef struct my_structure{
    char* str1;
    char* str2;
}MyStruct;

和一个返回 MyStruct 指针的函数:

MyStruct* foo();

在 foo 内部,我为 MyStruct 、 str1 和 str2 分配了内存,如下所示:

MyStruct* obj = malloc(sizeof(MyStruct));

obj.str1 = malloc(256);
obj.str2 = malloc(256);

我想从 python、java、C# 和 PHP 调用 foo我不想在这个过程中出现任何内存泄漏。

我不确定写入:

%newobject foo;
MyStruct* foo();

是否保证垃圾收集器将为结构及其内部的字符串释放内存。

我不想让调用者有义务为 str1 和 str2 显式释放内存,因为我正在寻找一种自动释放内存的方法。这可能吗?

在这种情况下我必须使用“newfree”类型映射吗?

如果您能为我提供一个示例来展示实现此目的的最佳方法,我将不胜感激。

谢谢!

In my C code, I have the following structure :

typedef struct my_structure{
    char* str1;
    char* str2;
}MyStruct;

And a function that returns a MyStruct pointer :

MyStruct* foo();

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);

I want to call foo from python, java, C# and PHP and I don't want to have any memory leak in this process.

I am not sure if writing:

%newobject foo;
MyStruct* foo();

guarantees that the garbage collector will free memory for both the structure and the strings inside it.

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?

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.

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

偏闹i 2024-10-16 19:47:32

typemap(newfree) 立即释放返回的 %newobject 使用的内存,例如当 char* 返回值转换为 Python 字符串并且分配的对象不再是时需要。我认为您想要的是 %extend SWIG 围绕您的 C 结构生成的类包装器以提供析构函数:

%newobject foo;

%extend MyStruct {
    ~MyStruct() {
       free($self->str1);
       free($self->str2);
    }
}

如果这解决了您的问题,请发表评论。这是基于我自己的实验,我可以在 SWIG 文档中找到并在我生成的简单包装器中正常工作。

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);
    }
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文