编写 Python C 扩展:如何正确加载 PyListObject?
在尝试读取充满浮点数的 Python 列表并用它们的值填充 real Channels[7]
(我使用的是 F2C,所以 real 只是 float 的 typedef)时,我所能做的就是从中检索的是零值。你能指出下面代码中的错误吗?
static PyObject *orbital_spectra(PyObject *self, PyObject *args) {
PyListObject *input = (PyListObject*)PyList_New(0);
real channels[7], coefficients[7], values[240];
int i;
if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &input)) {
return NULL;
}
for (i = 0; i < PyList_Size(input); i++) {
printf("%f\n", PyList_GetItem(input, (Py_ssize_t)i)); // <--- Prints zeros
}
//....
}
While attempting to read a Python list filled with float numbers and to populate real channels[7]
with their values (I'm using F2C, so real is just a typedef for float), all I am able to retrieve from it are zero values. Can you point out the error in the code below?
static PyObject *orbital_spectra(PyObject *self, PyObject *args) {
PyListObject *input = (PyListObject*)PyList_New(0);
real channels[7], coefficients[7], values[240];
int i;
if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &input)) {
return NULL;
}
for (i = 0; i < PyList_Size(input); i++) {
printf("%f\n", PyList_GetItem(input, (Py_ssize_t)i)); // <--- Prints zeros
}
//....
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
PyList_GetItem
将返回一个PyObject*
。您需要将其转换为 C 可以理解的数字。尝试将您的代码更改为:PyList_GetItem
will return aPyObject*
. You need to convert that to a number C understands. Try changing your code to this:我在这段代码中看到的东西很少。
PyListObject
。PyList_GetItem
返回一个PyObject
,而不是浮点数。使用 PyFloat_AsDouble 提取值。PyList_GetItem
返回NULL
,则抛出异常,您应该检查它。Few things I see in this code.
PyListObject
.PyList_GetItem
returns aPyObject
, not a float. UsePyFloat_AsDouble
to extract the value.PyList_GetItem
returnsNULL
, then an exception has been thrown, and you should check for it.