我有一个用 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 中找到答案.
Noneis not compatible with any C type. To accommodate for this, the default behavior is for functions with cdefed parameters to also acceptNone.
- If you want to consider
Noneinvalid input, then you need to write code that checks for it, and raised an appropriate exception.
解决方案是在编写时手动检查 None 并传递 NULL。
