Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...