动态分配和删除内存

Dynamically allocating and removing memory

在 Python 中 mallocfree 可能 吗?

import ctypes

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

我知道这样做很糟糕,因为 Python 是垃圾收集器,但我只想知道这是否可能。

是的,您可以调用从 DLL 导出的任何 C 函数,包括 C 运行时库 DLL,前提是您使用 .argtypes.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)