gpt4 book ai didi

c++ - 将 PyArrayObject* 转换为 int* 失败

转载 作者:行者123 更新时间:2023-11-30 17:10:08 24 4
gpt4 key购买 nike

我有一个非常简短的问题。任何人都可以解释一下为什么当我将 Numpy 整数数组传递给我的 C 代码时,我无法检索到正确的值?我的猜测是int C 中的类型与默认的 Numpy 不同,但坦率地说,我在在线文档中迷失了方向。这是我的案例:

在Python模块中我有一个字典

from numpy import * 

pars = {...,
'ICs' : array([0,1,2])
}

然后我将此字典传递给我的 C 函数

#include <Python.h>
#include <numpy/arrayobject.h>

...
...
int main(){
int i, *ics;

//That is the assignment according to the manual
ics = (int*)((PyArrayObject*)PyDict_GetItemString(pardict,"ICs"))->data);
for(i=0;i<9;i++) printf("\ni=%d\t-->%d",i,ics[i]);
return 0;
}

然后执行后,我得到的是:

i=0-->0
i=1-->0
i=2-->1
i=3-->0
i=4-->2
i=5-->0
i=6-->9102
i=7-->-289
i=8-->2910103
i=9-->294921

我本来希望看到我的三个整数被打印为 i<3 。如有任何澄清,我们将不胜感激!

提前致谢!

最佳答案

您需要使用正确的函数来访问底层数组,即PyArray_BYTES,如 http://docs.scipy.org/doc/numpy/reference/c-api.array.html 中所述。 .

但是请注意,这会直接访问缓冲区,而不考虑步幅!

关于c++ - 将 PyArrayObject* 转换为 int* 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33021326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com