chris
chris

Reputation: 11

how to call a c-function expecting a pointer to a structure with ctypes?

I face the following problem. In C I wrote the following:

#include <stdio.h>
typedef struct {
double *arr;
int length;
} str;

void f(str*);

int main (void){
   double x[3] = {0.1,0.2,0.3};
   str aa;
   aa.length = 3;
   aa.arr = x;
   f(&aa);
   return 0;
}

void f(str *ss){
   int i;
   printf("%d\n",ss->length);
   for (i=0; i<ss->length; i++) {
      printf("%e\n",ss->arr[i]);
   }
}

If I compile it to an executable it works correctly. I receive:

 3
 0.1
 0.2
 0.3

as it should be. After building the shared library 'pointertostrucCtypes.so' from the C-code above I call the function f in python as follows:

ptrToDouble = ctypes.POINTER(ctypes.c_double)
class pystruc (ctypes.Structure):
   _fields_=[
             ("length",ctypes.c_int),
             ("arr",ptrToDouble)
            ]
aa = pystruc()
aa.length = ctypes.c_int(4)
xx = numpy.arange(4,dtype=ctypes.c_double)
aa.arr = xx.ctypes.data_as(ptrToDouble)
myfunc = ctypes.CDLL('pointertostrucCtypes.so')
myfunc.f.argtypes = [ctypes.POINTER(pystruc)]

myfunc.f(ctypes.byref(aa))

It results always in printing out an arbitrary integer and afterwards it gives me a segmentation fault. because length does not fit. Has somebody an idea what I do wrong here ?

Upvotes: 1

Views: 1000

Answers (1)

Remy Blank
Remy Blank

Reputation: 4285

Your fields are reversed. Try:

class pystruc (ctypes.Structure):
    _fields_=[
             ("arr",ptrToDouble)
             ("length",ctypes.c_int),
            ]

Upvotes: 3

Related Questions