Python ctypes从void *创建bytearray

时间:2019-01-25 01:47:04

标签: python ctypes

我使用ctypes调用c函数

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

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

1 个答案:

答案 0 :(得分:0)

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

mytype = ctypes.c_char * my_len

然后尝试创建由您的C函数返回的from_address类型的实例:

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

请参见this question,其中malloc被用作数据源。