Python C扩展-为什么将使用关键字参数的方法强制转换为PyCFunction [英] Python C Extension - Why are methods that use keyword arguments cast to PyCFunction
问题描述
我正在学习Python-C扩展,并对为什么必须将使用关键字参数的方法强制转换为PyCFunctions感到困惑.
I've am learning about Python-C extensions and am puzzled as to why methods that use keyword arguments must be cast to PyCFunctions.
我对PyCFunction的理解是,它需要两个指向PyObject的指针,并返回一个指向PyObject的指针-例如.
My understanding of a PyCFunction is that it takes two pointers to PyObjects and returns a single pointer to a PyObject - e.g.
PyObject* myFunc(PyObject* self, PyObject* args)
如果我要使用使用关键字参数的函数,则此函数将使用三个指向PyObject的指针,并返回指向PyObject的单个指针-例如.
If I'm going to use a function that uses keyword arguments, then this function will take three pointers to PyObjects and returns a single pointer to a PyObject - e.g.
PyObject* myFunc(PyObject* self, PyObject* args, PyObject* keywordArgs)
但是,当我创建模块函数数组(用于名为"adder"的函数)时:
However, when I create the module functions array (for a function called 'adder'):
{ "adder", (PyCFunction)adder, METH_VARARGS | METH_KEYWORDS, "adder method" }
正常工作.感觉就像我将一个float转换为一个int并仍然必须使用float的非整数部分一样.如果我没有看到这项工作,我会以为那是行不通的.我在这里不明白什么?
works fine. It feels like I cast a float to an int and still got to use the non-integer parts of the float. If I didn't see this work, I would have thought it wouldn't work. What am I not understanding here?
此外,我看到了一些对PyCFunctionWithKeywords的引用,这些引用似乎具有我认为我需要的功能签名,但是我的编译器抱怨(发出警告)不兼容的指针类型".
Also, I saw some references to a PyCFunctionWithKeywords, which seems to have the function signature I thought I needed, but my compiler complained (gave warnings) about 'incompatible pointer types'.
不赞成使用PyCFunctionWithKeywords吗?如果没有,我是否应该/必须使用它?
Was PyCFunctionWithKeywords deprecated? If not, is there a time when I should/must use it?
推荐答案
如果您的函数处理关键字参数,则它必须对应于PyCFunctionWithKeywords.但是,C并不会进行重载,并且PyMethodDef构建的结构被定义为具有PyCFunction,而不是完全未经检查的void *.因此,您必须将PyCFunctionWithKeywords强制转换为PyCFunction才能阻止编译器抱怨.
If your function handles keyword arguments, then it must correspond to a PyCFunctionWithKeywords. However, C doesn’t do overloading, and the structure built by PyMethodDef is defined to expect a PyCFunction, rather than, say, a completely unchecked void *. So you must cast your PyCFunctionWithKeywords to a PyCFunction to stop the compiler complaining, that’s all.
请记住,您还必须在标志中传递METH_KEYWORDS,以告诉Python您的函数具有PyCFunctionWithKeywords的签名,而不是PyCFunction的签名.
Remember that you must also pass METH_KEYWORDS in the flags to tell Python that your function has the signature of a PyCFunctionWithKeywords, not a PyCFunction.
这篇关于Python C扩展-为什么将使用关键字参数的方法强制转换为PyCFunction的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!