我试图为python3编写一个C扩展模块,比如foo
,并且我试图定义可以接受关键字参数的方法。在
static PyObject* fooImpl(PyObject*, PyObject*, PyObject*);
static PyObject* fooImpl2(PyObject, PyObject*);
static PyMethodDef fooMethods[] = {
{"foo_impl", (PyCFunction) fooImpl, METH_VARARGS | METH_KEYWORDS, "Some description"},
{"foo_impl2", fooImpl2, METH_VARARGS, "Some description"},
{NULL, NULL, 0, NULL}
};
PyObject* fooImpl(PyObject* self, PyObject* args, PyObject* kwds) {
static const char *keywordList[] = { "kw1", "kw2", NULL};
PyObject *input = nullptr;
PyObject *kw1Val = nullptr;
PyObject *kw2Val = nullptr;
PyObject *returnVal = nullptr;
int err = PyArg_ParseTupleAndKeywords(args, kwds, "O|OO",
const_cast<char**>(keywordList),
&input, &kw1Val, &kw2Val);
if (!err) {
return NULL;
}
//// Do something with args to compute returnVal
return returnVal;
}
当我在python中尝试此操作时,我得到以下错误
^{pr2}$似乎解释器没有在PyMethodDef
中注册METH_KEYWORDS
标志。有没有其他方法可以在Python3的C扩展中添加PyCFunctionWithKeywords
方法。我找到的唯一来源是thisstackoverflow post,它可以追溯到Python文档here
任何帮助都是非常感谢的
你没有定义所有的关键字。即使参数是非可选的,它仍然需要定义一个名称,以便可以通过关键字或位置方式传递(因此
PyArg_ParseTupleAndKeywords
可以用关键字匹配位置,以防可选参数是按位置传递的)。基本上,关键字名称的数量必须始终与要解析的最大参数数匹配。在更改:
收件人:
^{pr2}$显然,您可以随意命名第一个参数;我只是匹配了C变量名。在
相关问题 更多 >
编程相关推荐