爲了模擬在python以下幾點:
def keywords(a, b, foo=None, bar=None, baz=None):
pass
下面的工作:
static PyObject *keywords(PyObject *self, PyObject *args, PyObject *kwargs) {
char *a;
char *b;
char *foo = NULL;
char *bar = NULL;
char *baz = NULL;
// Note how "a" and "b" are included in this
// even though they aren't supposed to be in kwargs like in python
static char *kwlist[] = {"a", "b", "foo", "bar", "baz", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "ss|sss", kwlist, &a, &b, &foo, &bar, &baz)) {
return NULL;
}
printf("a is %s\n", a);
printf("b is %s\n", b);
printf("foo is %s\n", foo);
printf("bar is %s\n", bar);
printf("baz is %s\n", baz);
Py_RETURN_NONE;
}
// ...
static PyMethodDef SpamMethods[] = {
//...
{"keywords", (PyCFunction) keywords, METH_VARARGS | METH_KEYWORDS, "practice kwargs"},
{NULL, NULL, 0, NULL}
,並使用它:
from spam import keywords
keywords() // Fails, require a and b
keywords('a') // fails, requires b
keywords('a', 'b')
keywords('a', 'b', foo='foo', bar='bar', baz='baz)
keywords('a', 'b','foo', 'bar', 'baz')
keywords(a='a', b='b', foo='foo', bar='bar', baz='baz')
而不僅僅是C API文檔,有在http://docs.python.org/2/extending/extending.html – timbo