繁体   English   中英

动态分配和删除 memory

[英]Dynamically allocating and removing memory

在 Python 中是否可以使用mallocfree之类的东西?

import ctypes

pointer = ctypes.malloc(10) # is this possible?
...
ctypes.free(pointer)

我知道这样做是一个可怕的想法,因为 Python 是垃圾收集的,但我只想知道这是否可能。

是的,您可以调用从 DLL 导出的任何 C function,包括 C 运行时库 DLL,前提是您使用.argtypes和 .restype 正确配置了.restype

import ctypes as ct

dll = ct.CDLL('msvcrt')  # Windows C runtime

# void* malloc(size_t size);
dll.malloc.argtypes = ct.c_size_t,
dll.malloc.restype = ct.c_void_p
# void free(void* ptr);
dll.free.argtypes = ct.c_void_p,
dll.free.restype = None

ptr = dll.malloc(100)
dll.free(ptr)

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM