从 Cython 将原始指针传递给 C 函数

Passing primitive pointers to C function from Cython

我正在围绕我们正在维护的 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 Whosebug.

    return aValue

我尝试使用的 C 函数的原型是:

unsigned long library_get_data_val(unsigned long device, int channel,
    int index, unsigned short *pValue);

库函数 returns aValue 参数中的请求值。它只是一个 unsigned short 原语。从这些类型的函数返回原语(即不是 struct)的预期方式是什么?我是 Cython 的新手,所以答案可能很简单,但我没有通过 Google.

看到任何明显的东西

我认为问题是你没有正确定义 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 函数,并且会很高兴。

(经过编辑,与我原来的答案有很大不同,我误解了问题!)

我发现了我的问题所在。您现在可能已经知道我已经编辑了问题。 company.pxd 文件由 .pyx 文件 cimport 编辑。一旦我将 C 原型复制到 company.pxd 中,它就起作用了。

我还需要在调用中使用 lib 前缀:

err = lib.library_get_data_val(device, channel, index, &aValue) # line 6