#先上代码再解释
static PyObject *keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds)
{
int voltage;
char *state = "a stiff";
char *action = "voom";
char *type = "Norwegian Blue";
static char *kwlist[] = {"voltage", "state", "action", "type", NULL};
if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
&voltage, &state, &action, &type))
return NULL;
printf("-- This parrot wouldn't %s if you put %i Volts through it.\n",
action, voltage);
printf("-- Lovely plumage, the %s -- It's %s!\n", type, state);
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef keywdarg_methods[] = {
/* The cast of the function is necessary since PyCFunction values
* only take two PyObject* parameters, and keywdarg_parrot() takes
* three.
*/
{"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS | METH_KEYWORDS,
"Print a lovely skit to standard output."},
{NULL, NULL, 0, NULL} /* sentinel */
};
PyObject * initkeywdarg(void)
{
/* Create the module and add the functions */
return Py_InitModule("keywdarg", keywdarg_methods);
}
这是一个函数(keywdarg_parrot)即使用了元组参数,也使用了字典参数的例子。例子出自Python2.7.2的文档。具体在:
Python v2.7.2 documentation »Extending and Embedding the Python
Interpreter
这个页面下。文档里面有一些关于C/C++与Python交互的介绍和例子,还是比较详细的。传递字典参量要注意,
{"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS | METH_KEYWORDS,
"Print a lovely skit to standard output."},
这里的METH_VARARGS | METH_KEYWORDS,与普通的不同。解析用:
PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
&voltage, &state, &action, &type)
其中的四个变量要提前声明好,这里分别是int,str,str,str类型的。int对应的是args接受到的值。string的都是keywds里面的,它们都是有初始值的。kwlist是变量的名字,就是在python里调用的时候使用的keyword名称。照着例子的模式可以改成其它的,能用的。具体是怎么工作的,其实我也太明白。
Python代码是这样的调用的时候:
print keywdarg.parrot(10,"LHJ",'HKJ','ER')
print keywdarg.parrot(10,"LHJ",'HKJ')
print keywdarg.parrot(10,"LHJ",type='KJ')
输出分别是:
-- This parrot wouldn't HKJ if you put 10 Volts through it.
-- Lovely plumage, the ER -- It's LHJ!
None
-- This parrot wouldn't HKJ if you put 10 Volts through it.
-- Lovely plumage, the Norwegian Blue -- It's LHJ!
None
-- This parrot wouldn't voom if you put 10 Volts through it.
-- Lovely plumage, the KJ -- It's LHJ!
None
第二次调用省略掉了变量,也能正常执行。第三次调用,变量type本来是第四位的,现在变成了keyword并写在了第三位,是python代码里调用的常见形式:keyword不讲顺序,省略掉的keyword使用了默认值。
就这些了,其它的你再看一下Python的文档吧。