[英]Parsing unsigned ints (uint32_t) in python's C api
If I write a function accepting a single unsigned integer ( 0
- 0xFFFFFFFF
), I can use: 如果我写的函数接受单个无符号整数(
0
- 0xFFFFFFFF
),我可以使用:
uint32_t myInt;
if(!PyArg_ParseTuple(args, "I", &myInt))
return NULL;
And then from python, I can pass an int
or long
. 然后从python中,我可以传递一个
int
或long
。
But what if I get passed a list of integers? 但是,如果我传递了整数列表怎么办?
uint32_t* myInts;
PyObject* pyMyInts;
PyArg_ParseTuple(args, "O", &pyMyInts);
if (PyList_Check(intsObj)) {
size_t n = PyList_Size(v);
myInts = calloc(n, sizeof(*myInts));
for(size_t i = 0; i < n; i++) {
PyObject* item = PyList_GetItem(pyMyInts, i);
// What function do I want here?
if(!GetAUInt(item, &myInts[i]))
return NULL;
}
}
// cleanup calloc'd array on exit, etc
Specifically, my issue is with dealing with: 具体来说,我的问题是处理:
int
s and long
s int
和long
的混合的列表 You could create a tuple and use the same method you used for a single argument. 您可以创建一个元组,并使用与单个参数相同的方法。 On the C side, the tuple objects are not really immutable, so it wouldn't be to much trouble.
在C端,元组对象并不是真正不变的,因此不会有太多麻烦。
Also PyLong_AsUnsignedLong
could work for you. PyLong_AsUnsignedLong
也可以为您工作。 It accepts int and long objects and raises an error otherwise. 它接受int和long对象,否则引发错误。 But if
sizeof(long)
is bigger than 4, you might need to check for an upper-bound overflow yourself. 但是,如果
sizeof(long)
大于4,则可能需要自己检查上限溢出。
static int
GetAUInt(PyObject *pylong, uint32_t *myint) {
static unsigned long MAX = 0xffffffff;
unsigned long l = PyLong_AsUnsignedLong(pylong);
if (l == -1 && PyErr_Occurred() || l > MAX) {
PyErr_SetString(PyExc_OverflowError, "can't convert to uint32_t");
return false;
}
*myint = (uint32_t) l;
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.