我使用的似乎就是PyArg_ParseTuple的usgae,但是代码仍然不能工作。我使用的是python 2.7
这是我正在编写的Python扩展的C代码:
static PyObject* tpp(PyObject* self, PyObject* args)
{
PyObject* obj;
PyObject* seq;
int i, len;
PyObject* item;
int arrayValue, temp;
if (!PyArg_ParseTuple(args, "O", &obj)){
printf("Item is not a list\n");
return NULL;
}
seq = PySequence_Fast(obj, "expected a sequence");
len = PySequence_Size(obj);
arrayValue = -5;
printf("[\n");
for (i = 0; i < len; i++) {
item = PySequence_Fast_GET_ITEM(seq, i);
// printf("%d : %d, PyArg: ", item, *item);
// PyArg_ParseTuple(item, "I", &temp);
PyObject* objectsRepresentation = PyObject_Repr(item);
const char* s = PyString_AsString(objectsRepresentation);
printf("%s\n", s);
PyObject* objType = PyObject_Type(item);
PyObject* objTypeString = PyObject_Repr(objType);
const char* sType = PyString_AsString(objTypeString);
printf("%s\n", sType);
if (PyArg_ParseTuple(item, "i", &arrayValue) != 0){
printf("%d\n", arrayValue);
printf("horray!\n");
}
}
Py_DECREF(seq);
printf("]\n");
printf("Item is a list!\n");
Py_RETURN_NONE;
}然后,我只需构建扩展并转到终端导入et,然后et.tpp(1,2)无法打印行if (PyArg_ParseTuple(item,"i",&arrayValue) != 0){ printf("%d\n",arrayValue);printf("horray!\n");}
我检查了列表中元素的类型,就像你在代码中看到的那样,它输出了'int‘。然而,由于某种原因,PyArg_ParseTuple出现了错误。
我需要能够访问python中列表中的信息以复制一些数据,将其传递到其他地方的C代码,然后将结果返回给python。
非常感谢!
发布于 2012-11-30 12:57:11
答案是使用long PyInt_AsLong(PyObject *io)
"long PyInt_AsLong(PyObject *io)将首先尝试将对象转换为PyIntObject,然后返回其值。如果存在错误,则返回-1,调用者应检查PyErr_Occurred()以确定是否存在错误,或者值是否恰好为-1。“
这是来自http://docs.python.org/2/c-api/int.html的,它是官方的c python int objects文档,其中包含所有相关的方法。
不幸的是,这只返回一个长值。但是,如果期望值很小,那么简单的强制转换就足够了。
发布于 2012-11-30 11:56:21
顾名思义,PyArg_ParseTuple()只解析元组。在您的代码中,item是一个整数,而不是一个元组。为了将int对象转换为C值,您需要使用arrayValue = PyInt_AsLong(item)。请注意,它返回一个C long,而不是int,因此您应该将arrayValue声明为long。
(编辑:之前我错误地提到了PyInt_FromLong。)
https://stackoverflow.com/questions/13636711
复制相似问题