我正在围绕我们正在维护的 C 库编写一个 Cython 包装器。我收到以下错误消息:
analog.pyx:6:66: Cannot convert 'unsigned short (*)' to Python object
这是我正在尝试编写的代码:
cimport company as lib
def get_value(device, channel, index):
cdef unsigned short aValue
err = library_get_data_val(device, channel, index, &aValue) # line 6
# Ignore the err return value for StackOverflow.
return aValue
我尝试使用的 C 函数的原型(prototype)是:
unsigned long library_get_data_val(unsigned long device, int channel,
int index, unsigned short *pValue);
库函数在 aValue
参数中返回请求的值。它只是一个 unsigned short
原语。从这些类型的函数返回原语(即不是 struct
)的预期方式是什么?我是 Cython 的新手,所以答案可能很简单,但我没有通过谷歌看到任何明显的东西。
最佳答案
我认为问题在于您没有正确定义 library_get_data_val
,因此 Cython 认为这是您正在调用的 Python 类型函数,并且不知道如何处理指向 aValue
尝试:
cdef extern from "header_containing_library_get_data_val.h":
# I've taken a guess at the signature of library_get_data_val
# Update it to match reality
int library_get_data_val(int device, int channel, int index, int* value)
这样 Cython 就知道它是一个需要指针的 C 函数,并且会很高兴。
(经过编辑,与我原来的答案有很大不同,我误解了问题所在!)
关于python - 从 Cython 将原始指针传递给 C 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29481319/