Di_ma
Di_ma

Reputation: 23

Ctypes, python. How to pass back a pointer to a C dynamically allocated double array in one of the function arguments?

I have a C function void get_data(int &len, double* data), which dynamically allocates the memory for data (size is not known in advance) and returns a pointer to the data. I would like to call it from python using ctypes.

The version with double* data = get_data(int &len) is working fine, but I need the one which passes the pointer via an argument, as I have several data vectors.

I've tried many different ways but nothing works:

fun = cfun.get_data
fun.argtypes = [ct.c_int, ct.POINTER(ct.c_int)]
fun.restype = None

len = ct.c_int()
data_ptr = ct.POINTER(ct.c_double)()

fun(len, data_ptr)

bool(data_ptr) -- NULL -- it's not mutable, so stays at NULL after the C function assigns the new value to it. I tried ct.byref(data_ptr), e.t.c. but haven't been able to get the data out.

Thanks a lot!

Upvotes: 2

Views: 1275

Answers (1)

fukanchik
fukanchik

Reputation: 2865

void get_data(int &len, double* data) which dynamically allocates the memory for data (size is not known in advance).

This won't work even in C. You passing value of a pointer into function. Changing this value won't be visible outside. You should have double** data ,e.g.pointer to pointer to double if you want to allocate inside of get_data and pass pointer outside.

void get_data(int *len, double** data)
{
  *len=12;
  *data=malloc(*len);

  //fill data
  for(i=0;i<*len;++i) (*data)[i]=<something>;

  return;
}

and here is your answer: Python and ctypes: how to correctly pass "pointer-to-pointer" into DLL?

Upvotes: 3

Related Questions