Skip to main content
 首页 » 编程设计

python之将 NULL 传递给 Cython 中的包装 C 函数

2025年05月04日14mq0036

我有一个用 Cython 封装的函数:

cdef extern  from "myheader.h": 
   int c_my_func (const_char *a, const_char* b) 

还有一个暴露给 Python 的函数:

def my_func(a, b): 
    c_my_func(a, b) 

函数 c_my_func 接受参数 a 和 b 的 NULL。当我从解释器调用它时:

my_func(None, None) 

它抛出异常:

TypeError: expected string or Unicode object, NoneType found 

如何使此函数接受 None 并将 NULL 传递给 c_my_func ?我不想手动检查 None 然后传递 NULL。我还尝试在 c_my_func 的 cdef 上使用默认参数,但它不起作用。

请您参考如下方法:

您可以在 Cython FAQ 中找到答案.

None is not compatible with any C type. To accommodate for this, the default behavior is for functions with cdefed parameters to also accept None.

  1. If you want to consider None invalid input, then you need to write code that checks for it, and raised an appropriate exception.

解决方案是在编写时手动检查 None 并传递 NULL。