首页 > 解决方案 > 如何为python中malloc创建的空间赋值?

问题描述

我试图在 python(Ubuntu 18.04 linux)中为 malloc 创建的空间分配一个值(字节),但不知道如何......

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

有人可以帮忙吗...

标签: linuxmallocpython-3.7ctypesmemcpy

解决方案


您不应该使用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)。


推荐阅读