Python Ctypes - 写入由 malloc 创建的内存

Python Ctypes - Writing to memory created by malloc

我有这样的东西:

import ctypes

dll = ctypes.CDLL('libc.so.6')

dll.malloc.argtypes = ctypes.c_size_t
dll.malloc.restype = ctypes.c_void_p

ptr: int = dll.malloc(100) # how do i write to this memory?
print(ptr) # gives a memory address

如何为该内存设置一个值?最好是ctypes.py_object.

我知道在 Python 中这样做是个坏主意,但我只是在尝试打破规则。

您可以写入类似于 C 的指针。将 void 指针转换为可以取消引用的内容并使用 Python 写入它或使用 ctypes 调用可以使用的 C 函数指针。几个例子:

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
# char* strcpy(char* dest, const char* src)
dll.strcpy.argtypes = ct.c_char_p, ct.c_char_p
dll.strcpy.restype = ct.c_char_p

# casting to pointer to specific-sized array enables
# use of ".raw" and checks that array bounds aren't exceeded.
ptr = ct.cast(dll.malloc(10), ct.POINTER(ct.c_char * 10))
print(ptr.contents.raw)
# Note use of [:] to replace the entire array contents with a same-sized bytes object
ptr.contents[:] = b'abcdefghij'
print(ptr.contents.raw)

# char (*ptr)(10) isn't correct for strcpy, so cast to char*
dll.strcpy(ct.cast(ptr, ct.POINTER(ct.c_char)), b'ABCDEFGHIJ')
print(ptr.contents.raw)
dll.free(ptr)

输出:

b'\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00'
b'abcdefghij'
b'ABCDEFGHIJ'