如何为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

有人可以帮忙吗...

解决方法

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...