python中malloc创建的space如何赋值?

How to assign a value to the space created by malloc in python?

我试图将一个值(字节)分配给由 malloc 在 python (Ubuntu 18.04 linux) 中创建的 space 但不知道如何...

dllc = CDLL("lib.so.6")
malloc = dll.malloc
malloc.restype = c_void_p
malloc.argtypes = (c_size_t,)

#initialize a pointer using malloc and allocate a space of size 1032
ptr = malloc(1032)

#here is the sample value of size 1032 in bytes
value = b'xxxxxxxxxxxxxxxxx......xxxxxxxx'

我实际上尝试使用 memcpy 复制值,但结果值与原始值不一样...

memcpy = dllc.memcpy
memcpy.restype = c_void_p
memcpy.argtype = (c_void_p, c_void_p, c_size_t)

#copy value to the space referenced by ptr
memcpy(ptr, id(value), 1032)

当我取消引用指针时,值与分配的值不同

import ctypes

#dereference the pointer but the value doesn't match
ctypes.cast(ptr, ctypes.py_object).value

有人可以帮忙吗...

您不应该使用 id,因为您可以将字节缓冲区传递给 memcpy

我在 windows,所以只有第一行不同,但其余代码应该有效:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import ctypes


def main():
    dll = ctypes.CDLL("msvcrt")
    malloc = dll.malloc
    malloc.restype = ctypes.c_void_p
    malloc.argtypes = (ctypes.c_size_t, )
    memcpy = dll.memcpy
    memcpy.restype = ctypes.c_void_p
    memcpy.argtypes = (ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t)

    alloc_size = 1032
    ptr = malloc(alloc_size)

    value = b"A" + b"X" * 1030 + b"B"

    assert len(value) == alloc_size

    # note that ctypes has a memmove method.
    # ctypes.memmove(ptr, value, alloc_size)
    memcpy(ptr, value, alloc_size)

    # cast the pointer to a char*
    pchar = ctypes.cast(ptr, ctypes.c_char_p)

    # print the first, some of the in-between and the last bytes.
    print(pchar.value[0], pchar.value[1:10], pchar.value[alloc_size - 1])

if __name__ == "__main__":
    main()

输出:

65 b'XXXXXXXXX' 66

还要注意 ctypes 有一个 memmove(所以你不需要 memcpy)。