我正在尝试将 numpy 数组传递到我想要更改数组值的 C 函数中。但我必须将索引乘以 2 才能使其正常工作。将值分配给奇数索引(假设为i
)会导致将垃圾分配给索引(i-1)/2
。这是源代码。
C:
#include "assign_array.h"
void assign(int *arr, int i) {
arr[i] = 2017;
}
Python:
import ctypes, numpy
lib2 = ctypes.cdll.LoadLibrary('./assign_array.so')
for i in range(5):
array = numpy.zeros(8, dtype = int)
ptr = array.ctypes.data_as(ctypes.POINTER(ctypes.c_int))
print('i = {}:'.format(i))
lib2.assign(ptr, i)
print(array)
为什么会发生这种情况?
最佳答案
这不完全是垃圾:2047
是 0x7e1
,8662949036032
是 0x7E100000000
>。看起来好像您正在混合不同的 C 编译器(或提供给 C 编译器的标志),因此 Python 认为 int
是 64 位,但您的 C 编译器认为 int
是32位的。但实际上,Python 中的 int
并不保证与 C 编译器中的 int
匹配;它可能更典型地匹配long
。
根据the numpy documentation ,dtype
可以指定为 numpy.int32
以特指 32 位 int
。这可能是处理此问题的最简单方法,或者当然您可以更改 C 代码以使用 long
(假设 C 编译器设置中为 64 位 long
) .
关于python - 当 numpy 数组被 C 函数改变时,魔法就发生了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43023462/