使用PyArg_ParseTuple解析用户定义的类型 [英] Parsing User Defined Types Using PyArg_ParseTuple
问题描述
如何使用PyArg_ParseTuple
解析用户定义的类型(或现有非标准库中的类型)?
How to parse userdefined types (or types from an existing non-standard library) using PyArg_ParseTuple
?
推荐答案
Instead of using the plain O
format, as Martijn suggested, I normally prefer using the O&
format. It allows you to pass a function that will be called to convert any PyObject*
to an arbitrary C (double) pointer. Here is some example usage, in which I'm converting a passed value to a pointer to my own object type:
/**
* 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.
}
然后,在此时需要解析对象:
Then, at the point you need to parse your object:
/**
* 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上,然后在同一功能的其他功能中重新使用它.
The advantage of this approach is that you can encapsulate your MyConverter
on a C-API and then re-use it in other functions for the the same job.
这篇关于使用PyArg_ParseTuple解析用户定义的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!