如何防止匿名对象的Python垃圾收集? [英] how to prevent Python garbage collection for anonymous objects?

查看:331
本文介绍了如何防止匿名对象的Python垃圾收集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个Python代码中

  import gc 
gc.disable()
MyClass()

我希望由 MyClass 构造函数不会被垃圾收集。 MyClass 实际上链接到C ++代码的共享对象库,并且通过原始内存指针我可以检查匿名对象的内容。

然后我可以看到对象立即被损坏(垃圾收集)。



如何防止Python垃圾收集的一切?



我必须保持匿名。我不能更改代码 MyClass()的部分 - 它必须保持原样。



MyClass()必须保持原样,因为它是C ++的精确翻译(通过SWIG),两者应该相同,以便翻译人员的利益。

我必须通过一些初始化代码来阻止垃圾收集,而这个初始化代码在程序开始时只调用一次。那之后我什么也碰不到。 gc 中引用的垃圾回收器仅用于 gc 用于解决循环引用。在Python中(至少在主要的C实现中,CPython)内存管理的主要方法是引用计数。在你的代码中, MyClass()的结果没有引用,所以总是立即处理。没有办法阻止这种情况发生。



什么是不明确的,即使是你的编辑,为什么你不能简单地将它分配给某些东西?如果目标受众是翻译人员,那么这些人可能大概会阅读,因此请写下评论,解释您为什么要完成作业。


In this Python code

import gc
gc.disable()
<some code ...>
MyClass()
<more code...>

I am hoping that the anonymous object created by MyClass constructor would not be garbage-collected. MyClass actually links to a shared object library of C++ code, and there through raw memory pointers I am able to inspect the contents of the anonymous object.

I can then see that the object is immediately corrupted (garbage collected).

How to prevent Python garbage collection for everything?

I have to keep this call anonymous. I cannot change the part of the code MyClass() - it has to be kept as is.

MyClass() has to be kept as is, because it is an exact translation from C++ (by way of SWIG) and the two should be identical for the benefit of people who translate.

I have to prevent the garbage collection by some "initialization code", that is only called once at the beginning of the program. I cannot touch anything after that.

解决方案

The "garbage collector" referred to in gc is only used for resolving circular references. In Python (at least in the main C implementation, CPython) the main method of memory management is reference counting. In your code, the result of MyClass() has no references, so will always be disposed immediately. There's no way of preventing that.

What is not clear, even with your edit, is why you can't simply assign it to something? If the target audience is "people who translate", those people can presumably read, so write a comment explaining why you're doing the assignment.

这篇关于如何防止匿名对象的Python垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆