将Numpy数组传递给具有Ctypes的C在Linux和Windows之间有所不同



我正试图将Numpy数组传递到C中,但在Windows和Linux中会得到不同的结果。

在Python 中

import platform
import numpy as np
import ctypes
if platform.system() == 'Windows':
c_fun = np.ctypeslib.load_library("/mypath/c_fun.dll", ".").c_fun
else:    # Linux
c_fun = np.ctypeslib.load_library("/mypath/c_fun.so", ".").c_fun
c_fun.argtypes = [np.ctypeslib.ndpointer(dtype=np.int, ndim=2, flags="C_CONTIGUOUS"), ctypes.c_int, ctypes.c_int]
array = np.array([[0, 1, 0], [0, 1, 0], [0, 1, 0]])
rows, cols = array.shape
c_fun(array, rows, cols)

In C

void c_fun(int* array, int rows, int cols)
{
for (int i = 0; i < rows * cols; i++)
printf("%d ", array[i]);
}

当我在Windows中运行该程序时,输出为"0 1 0 0 1 0 1 0",运行良好。

但在Linux中,输出是"0 0 1 0 0 0 0 1",为什么?

首先,不要使用numpy.int。它只是int,而不是任何NumPy的东西。我认为它是为了向后兼容性。

默认情况下,NumPy将Python int转换为dtypenumpy.int_(注意下划线(,numpy.int_对应于Clong,而不是Cint。因此,您的代码只有在intlong大小相同的情况下才能工作,因为它们在Windows上,而不是Linux上。

最新更新