首页 > 解决方案 > Python ctypes 从 void* 创建字节数组

问题描述

我使用 ctypes 来调用 ac 函数

void *crypto_data(void *buffer, int length, int *encrypt_len)
{
     void *encrypt = malloc(length+25);
     ...
     *encrypt_len = length + 25;
     return encrypt;
}

    lib.crypto_data.argtypes = [c_void_p, c_int, c_void_p]
    lib.crypto_data.restype = c_void_p

    my_len = c_int()
    out_buffer = c_int()
    out_buffer = lib.crypto_data(gzip_data, len(gzip_data), byref(my_len))
    print out_buffer #this out_buffer is the address of malloc

如何从这个分配的内存中创建字节数组?

标签: pythonctypes

解决方案


我相信您可以使用 c_char 或 c_uchar 和缓冲区长度创建一个新类型:

mytype = ctypes.c_char * my_len

然后尝试创建from_addressC 函数返回的该类型的实例:

addr = crypto_data(args...)
array_of_char = mytype.from_address(addr)

请参阅此问题where mallocis used as the source of the data。


推荐阅读