【问题标题】:Passing Numpy array to C with Ctypes differs between Linux and Windows使用 Ctypes 将 Numpy 数组传递给 C 在 Linux 和 Windows 之间有所不同
【发布时间】:2019-11-08 02:53:55
【问题描述】:

我正在尝试将 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”,为什么?

【问题讨论】:

    标签: python numpy ctypes


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-04-20
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多