返回C++;Python ctypes/numpy ctypeslib中的整数数组输出不正确
我试图创建一个C++函数,它将返回指向数组的指针,然后我可以在NUMPY中使用它。我似乎被困在最基本的问题上。当我打印出我得到的数组值(在本例中应该是数字0到99)时,在83之后,我没有得到预期的结果。当我问我的C++函数打印出数组的内容时,一切看起来都很好。有人知道这里发生了什么吗 编辑:返回C++;Python ctypes/numpy ctypeslib中的整数数组输出不正确,python,c++,arrays,numpy,ctypes,Python,C++,Arrays,Numpy,Ctypes,我试图创建一个C++函数,它将返回指向数组的指针,然后我可以在NUMPY中使用它。我似乎被困在最基本的问题上。当我打印出我得到的数组值(在本例中应该是数字0到99)时,在83之后,我没有得到预期的结果。当我问我的C++函数打印出数组的内容时,一切看起来都很好。有人知道这里发生了什么吗 编辑: ... ... 77 78 79 80 81 82 83 -23162618 -671088158 250053520 1 261248736 1 246869272 1 0 0 250053520 1 1
...
...
77
78
79
80
81
82
83
-23162618
-671088158
250053520
1
261248736
1
246869272
1
0
0
250053520
1
1359648784
32767
246824912
1
因此,我无法返回超出范围的变量。我明白。那么,如何将数组返回python,而不在参数中传递指向数组的指针呢
我的Python文件:
python_file.py
import ctypes
import itertools
import numpy as np
h_list=np.array(range(100), dtype=int)
length = len(h_list)
data = h_list.astype(np.int32)
lib = ctypes.CDLL('/Path/to/file/ctypes_test/hello.so')
mynum = lib.mynum
mynum.restype = np.ctypeslib.ndpointer(dtype=ctypes.c_int, shape=(length,), flags='C_CONTIGUOUS')
mynum.argtypes = [np.ctypeslib.ndpointer(ctypes.c_int, flags="C_CONTIGUOUS"),
ctypes.c_int]
h = mynum(data, length)
for i in h:
print i
截断的输出,正如您在83件事情发生后看到的:
输出:
...
...
77
78
79
80
81
82
83
-23162618
-671088158
250053520
1
261248736
1
246869272
1
0
0
250053520
1
1359648784
32767
246824912
1
< >我的C++文件:
你好。cpp
extern "C" {
int * mynum(int *hkls, int length){
int out [length];
for (int i = 0; i < length; i++) {
out[i]=hkls[i];
}
int * out_a = out;
return out_a;
}
}
在mynum()
返回局部变量的地址时,不应执行此操作:在mynum()
返回局部变量的地址时,不应执行此操作: