在cython中处理默认参数 我用Cython包装了一些C++代码,我不知道用默认值处理参数的最佳方法是什么。 我的C++代码中有参数默认值的函数。我想用这样一种方式来包装它们:如果没有给出参数,就可以使用这些默认值。有办法做到这一点吗

在cython中处理默认参数 我用Cython包装了一些C++代码,我不知道用默认值处理参数的最佳方法是什么。 我的C++代码中有参数默认值的函数。我想用这样一种方式来包装它们:如果没有给出参数,就可以使用这些默认值。有办法做到这一点吗,c++,python,cython,C++,Python,Cython,在这一点上,我能看到的提供选项参数的唯一方法是将它们定义为python代码的一部分(在下面pycode.pyx中的def funcsaement中),但是我不止一次地定义了默认值,这是我不想要的 cppcode.h: int init(const char *address=0, int port=0, int en_msg=false, int error=0); cdef extern from "cppcode.h": int func(char *address, int port,

在这一点上,我能看到的提供选项参数的唯一方法是将它们定义为python代码的一部分(在下面pycode.pyx中的
def func
saement中),但是我不止一次地定义了默认值,这是我不想要的

cppcode.h

int init(const char *address=0, int port=0, int en_msg=false, int error=0);
cdef extern from "cppcode.h":
int func(char *address, int port, int en_msg, int error)
cimport pycode_c
def func(address, port, en_msg, error):
    return pycode_c.func(address, port, en_msg, error)

pycode_c.pxd

int init(const char *address=0, int port=0, int en_msg=false, int error=0);
cdef extern from "cppcode.h":
int func(char *address, int port, int en_msg, int error)
cimport pycode_c
def func(address, port, en_msg, error):
    return pycode_c.func(address, port, en_msg, error)

pycode.pyx

int init(const char *address=0, int port=0, int en_msg=false, int error=0);
cdef extern from "cppcode.h":
int func(char *address, int port, int en_msg, int error)
cimport pycode_c
def func(address, port, en_msg, error):
    return pycode_c.func(address, port, en_msg, error)

可以使用不同的参数()声明函数:

其中:

它可以在Cython代码()中使用:

要在Python()中尝试它,请执行以下操作:

输出 Cython还有(在
*.pxd
文件中)可选参数:

cdef foo(x=*)

这种方法的问题在于,尽管C++限制了在列表末尾省略参数,但Python允许您使用关键字指定任何参数集。这意味着在pyx代码中,仅仅因为
error不是None
并不意味着
address
port
en_msg
具有合理的值。我想您可以使用可变长度参数列表定义python函数,
def init(*args)
,然后从那里开始。那么关键字顺序就不再是问题了。但这一切似乎有点丑陋。Cython显然对变量args有某种支持,但我不太理解FAQ中的示例:。@Andrew Aylett:正确。这取决于您希望有多严格:添加显式检查或在docstring中只提及调用约定。例如,您可以与
UNSET
对象进行比较,并为@amicitas的无效函数调用获取
TypeError
va_list
用于接受变量args的
C
函数;注意示例中的
cdef
不是
def