gpt4 book ai didi

c++ - 如何删除使用 SWIG 生成的 Python 包装器中的堆对象?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:24:09 26 4
gpt4 key购买 nike

我正在开发一个 Python 模块和一个 C++ 库。在 C++ 代码中,我有一个返回堆对象的函数,如下所示。

MyClass* func()
{
MyClass* myclass = new MyClass();
return myclass;
}

但是当我在Python端使用这个函数时,我无法删除返回的对象。

myclass = func()
del myclass # still remains in memory

谁能告诉我如何在 Python 代码中删除返回的对象?

我可以将返回值的类型从 MyClass* 更改为 MyClass,这样我就可以避免这种内存泄漏。但我不想触及 C++ 代码,因为 C++ 库已在其他地方使用。

最佳答案

参见 11.2 节中的 %newobject%typemap(newfree) 指令SWIG 的文档。

引用自文档:

A common problem in some applications is managing proper ownership of objects. For example, consider a function like this:

Foo *blah() {
Foo *f = new Foo();
return f;
}

If you wrap the function blah(), SWIG has no idea that the return value is a newly allocated object. As a result, the resulting extension module may produce a memory leak (SWIG is conservative and will never delete objects unless it knows for certain that the returned object was newly created).

To fix this, you can provide an extra hint to the code generator using the %newobject directive. For example:

%newobject blah;
Foo *blah();

%newobject works exactly like %rename and %exception. In other words, you can attach it to class members and parameterized declarations as before. For example:

%newobject ::blah();                   // Only applies to global blah
%newobject Object::blah(int,double); // Only blah(int,double) in Object
%newobject *::copy; // Copy method in all classes
...

When %newobject is supplied, many language modules will arrange to take ownership of the return value. This allows the value to be automatically garbage-collected when it is no longer in use. However, this depends entirely on the target language (a language module may also choose to ignore the %newobject directive).

Closely related to %newobject is a special typemap. The "newfree" typemap can be used to deallocate a newly allocated return value. It is only available on methods for which %newobject has been applied and is commonly used to clean-up string results. For example:

%typemap(newfree) char * "free($1);";
...
%newobject strdup;
...
char *strdup(const char *s);

In this case, the result of the function is a string in the target language. Since this string is a copy of the original result, the data returned by strdup() is no longer needed. The "newfree" typemap in the example simply releases this memory.

关于c++ - 如何删除使用 SWIG 生成的 Python 包装器中的堆对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15184799/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com