【发布时间】:2013-10-09 20:32:14
【问题描述】:
如何使用PyArg_ParseTuple 解析用户定义的类型(或来自现有非标准库的类型)?
【问题讨论】:
标签: python python-2.7 python-c-api python-bindings
如何使用PyArg_ParseTuple 解析用户定义的类型(或来自现有非标准库的类型)?
【问题讨论】:
标签: python python-2.7 python-c-api python-bindings
我通常更喜欢使用 O& format,而不是像 Martijn 建议的那样使用普通的 O 格式。它允许您传递一个函数,该函数将被调用以将任何 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.
}
然后,你需要解析你的对象:
/**
* 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. */
}
这种方法的优点是您可以将 MyConverter 封装在 C-API 上,然后在其他函数中重复使用它来完成相同的工作。
【讨论】:
可以使用O format解析自定义python类:
O(对象)[PyObject *]
将 Python 对象(无需任何转换)存储在 C 对象指针中。 C 程序因此接收传递的实际对象。对象的引用计数不会增加。存储的指针不是NULL。
【讨论】: