7

采用如下定义的规范 Python 函数:

def foo(*args, **kwargs):
  print("args:", len(args))
  for i in args:
    print(i)

  print("kwargs:", len(kwargs))
  for k in kwargs:
    print(k, kwargs[k])

从 Python 调用此函数可能如下所示:

some_list = ['one', 'two', 'three']
some_kwords = { "name1" : "alice", "name2" : "bob", "name3" : "carol" }

foo(*some_list, **some_kwords)

Python C API 是否提供了某种从 C 空间调用此函数的方法?如何将以上三行转换为 C 等效项?

请注意,在一个类似的问题中,使用boost::pythonC++ 调用这个关键字参数函数,其语法与 Python 几乎相同,这真是一个技巧!

4

1 回答 1

5

要在 Python/C 中调用具有任意位置和关键字参数的函数,等效于function(*args, **kwds)语法,请使用PyObject_Call

/* error checking omitted for brevity */
PyObject *some_list = PyObject_BuildValue("(sss)", "one", "two", "three");
PyObject *some_kwords = PyObject_BuildValue("{s:s,s:s,s:s}",
                          "name1", "alice", "name2", "bob", "name3", "carol");
PyObject *ret = PyObject_Call(foo, some_list, some_kwords);
Py_DECREF(some_list);
Py_DECREF(some_kwords);
于 2013-01-17T03:49:39.660 回答