Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing memoryview to C function

I have a C function declared as follows:

void getIndexOfState(long *p, long C, long G, long B, long *state);

Nowadays my cython wrapper code uses the buffer syntax from numpy array:

cpdef int getIndexOfState(self, np.ndarray[np.int_t, ndim=1, mode="c"] s):
    cdef long out
    getIndexOfState(&out, self.C, self.G, self.B, <long*> s.data)
    return out

I want to use the new memoryview syntax, my question is, how can I pass the pointer to the data when using a memoryview?

I tried:

cpdef int getIndexOfState(self, long[:] s):
    cdef long out
    getIndexOfState(&out, self.C, self.G, self.B, s)
    return out

which raised the "Cannot assign type 'long[:]' to 'long *'" error when I was trying to compile the module. There is any way to pass that pointer without coercing the memoryview back to a numpy array before calling the C function?

like image 766
flaviotruzzi Avatar asked Jan 29 '13 13:01

flaviotruzzi


1 Answers

If the underlying data is properly contiguous/strided and there is at least one element in the memory, then it should suffice to pass a pointer to the first element (and maybe the length):

getIndexOfState(&out, self.C, self.G, self.B, &s[0])

EDIT:

One way to ensure "properly contiguous" should be the addition of "[::1]".

cpdef int getIndexOfState(self, long[::1] s):
    cdef long out
    getIndexOfState(&out, self.C, self.G, self.B, &s[0])
    return out
like image 81
Fred Foo Avatar answered Oct 04 '22 21:10

Fred Foo