c – 如何删除使用SWIG生成的Python包装器中的堆积对象?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c – 如何删除使用SWIG生成的Python包装器中的堆积对象?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2414字,纯文字阅读大概需要4分钟。
内容图文
![c – 如何删除使用SWIG生成的Python包装器中的堆积对象?](/upload/InfoBanner/zyjiaocheng/744/91fd22f85e2649d48fb848b6a2b9b863.jpg)
我正在开发一个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库已经在另一个地方使用了.
解决方法:
请参阅SWIG文档的第11.2节中的%newobject和%typemap(newfree)指令.
引自文档:
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包装器中的堆积对象?全部内容,希望文章能够帮你解决c – 如何删除使用SWIG生成的Python包装器中的堆积对象?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。