将memoryview传递给C函数 [英] Passing memoryview to C function

查看:72
本文介绍了将memoryview传递给C函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个声明如下的C函数:

I have a C function declared as follows:

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

如今,我的cython包装器代码使用了numpy数组中的缓冲区语法:

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

我想使用新的memoryview语法,我的问题是,使用memoryview时如何将指针传递给数据?

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

我尝试过:

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

在尝试编译模块时,出现了无法将类型'long [:]'分配给'long *'"的错误.有什么方法可以在调用C函数之前将指针传递给numpy数组而不用将其强制转换为numpy数组?

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?

推荐答案

如果基础数据是

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])

确保适当连续"的一种方法是添加"[:: 1]".

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

这篇关于将memoryview传递给C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆