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

Passing Numpy array to C with Ctypes differs between Linux and 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)

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 0 1 0”,运行良好。

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

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

NumPy默认将Python ints转为dtype numpy.int_(注意下划线),numpy.int_对应C long,不是 C int。因此,您的代码仅在 C intlong 大小相同时有效,它们在 Windows 上,但在 Linux.

上无效