0

I use ctypes to call a c function

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

how do I create bytearray from this malloced memory?

liaogang
  • 508
  • 3
  • 16

1 Answers1

0

I believe you can create a new type using c_char or c_uchar and the buffer length:

mytype = ctypes.c_char * my_len

Then try to create an instance of that type from_address returned by your C function:

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

See this question where malloc is used as the source of the data.

aghast
  • 14,785
  • 3
  • 24
  • 56