简体   繁体   English

ctypes内存管理:如何以及何时释放分配的资源?

[英]ctypes memory management: how and when free the allocated resources?

I'm writing a small wrapper for a C library in Python with Ctypes, and I don't know if the structures allocated from Python will be automatically freed when they're out of scope. 我正在用Ctypes在Python中为C库编写一个小包装器,我不知道从Python分配的结构是否会在超出范围时自动释放。

Example: 例:

from ctypes import *
mylib = cdll.LoadLibrary("mylib.so")

class MyPoint(Structure):
    _fields_ = [("x", c_int), ("y", c_int)]

def foo():
    p = MyPoint()
    #do something with the point

foo()

Will that point still be "alive" after foo returns? 在foo返回后,这一点仍然“活着”吗? Do I have to call clib.free(pointer(p)) ? 我是否必须调用clib.free(pointer(p)) or does ctypes provide a function to free memory allocated for C structures? 或者ctypes是否提供释放为C结构分配的内存的函数?

In this case your MyPoint instance is a Python object allocated on the Python heap, so there should be no need to treat it differently from any other Python object. 在这种情况下,您的MyPoint实例是在Python堆上分配的Python对象,因此不需要将其与任何其他Python对象区别对待。 If, on the other hand, you got the MyPoint instance by calling say allocate_point() in mylib.so , then you would need to free it using whatever function is provided for doing so, eg free_point(p) in mylib.so . 另一方面,如果你通过在mylib.so调用say allocate_point()得到MyPoint实例,那么你需要使用为此提供的任何函数释放它,例如mylib.so free_point(p)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 什么时候ctypes释放内存? - When does ctypes free memory? Python:Ctypes 如何检查 memory 管理 - Python: Ctypes how to check memory management Python ctypes 指针和分配的内存 - Python ctypes pointer and allocated memory Python ctypes:如何释放内存? 获取无效指针错误 - Python ctypes: how to free memory? Getting invalid pointer error 在具有ctypes的cuda分配的内存上使用python句柄 - Using python handles on cuda allocated memory with ctypes 释放在Python中通过ctypes分配的内存 - Freeing memory allocated via ctypes in Python Python print() 损坏由 ctypes 分配的 memory - Python print() corrupting memory allocated by ctypes 为什么即使在 TPU 上训练时 tensorflow 也会吃掉这么多 RAM 以及如何释放训练后分配的内存 - Why tensorflow eats up so many RAM even when training on TPU & how to free the memory allocated after training 删除Python对象时,Ctypes Structures和POINTERS是否自动释放内存? - Does Ctypes Structures and POINTERS automatically free the memory when the Python object is deleted? 如何释放外部C库分配的内存与Cython模块的接口,其中内存最终返回到Python进程? - How to free memory allocated by external C libraries interfacing with Cython module where the memory is ultimately returned to a Python process?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM