dha*_* sr 6 python python-c-api python-2.7 python-bindings
如何使用 解析用户定义的类型(或来自现有非标准库的类型)PyArg_ParseTuple?
不像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 上,然后在其他函数中重新使用它来完成相同的工作。