使用 PyArg_ParseTuple 解析用户定义的类型

dha*_* sr 6 python python-c-api python-2.7 python-bindings

如何使用 解析用户定义的类型(或来自现有非标准库的类型)PyArg_ParseTuple

And*_*jos 5

不像OMartijn 建议的那样使用普通格式,我通常更喜欢使用O&format。它允许您传递一个函数,该函数将被调用以将 any 转换PyObject*为任意 C(双)指针。这是一些示例用法,其中我将传递的值转换为指向我自己的对象类型的指针:

/** 
 * This method should return 0 if it does not work or 1 in case it does
 * PyArg_*() functions will handle the rest from there or let your program
 * continue in case things are fine.
 */
int MyConverter(PyObject* o, MyOwnType** mine) {
  //write the converter here.
}
Run Code Online (Sandbox Code Playgroud)

然后,此时您需要解析您的对象:

/**
 * Simple example
 */
static PyObject* py_do_something(PyObject*, PyObject* args, PyObject* kwds) {

    /* Parses input arguments in a single shot */
    static char* kwlist[] = {"o", 0};

    MyOwnType* obj = 0; ///< if things go OK, obj will be there after the next call

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kwlist, &MyConverter, &obj))
      return 0; ///< we have failed, let Python check exceptions.

    /* if you get to this point, your converter worked, just use */
    /* your newly allocated object and free it, when done. */

}
Run Code Online (Sandbox Code Playgroud)

这种方法的优点是您可以将您MyConverter的 C-API封装在 C-API 上,然后在其他函数中重新使用它来完成相同的工作。


Mar*_*ers 3

自定义 python 类可以使用以下O格式进行解析进行解析:

\n\n
\n

O(对象)[PyObject *]
\n 将 Python 对象(不进行任何转换)存储在 C 对象指针中。因此,C 程序接收传递的实际对象。对象\xe2\x80\x99s 引用计数未增加。存储的指针不为NULL。

\n
\n