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

我试图将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,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 0 1 0”,效果很好。

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

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

首先,不要使用numpy.int。只是int,不是任何NumPy事物。我认为这里是为了向后兼容。

NumPy默认将Python int转换为dtype numpy.int_(请注意下划线),而numpy.int_对应于C long ,而不是C {{1} }。因此,仅当C intint的大小与Windows相同但Linux相同时,您的代码才能工作。

本文链接:https://www.f2er.com/3140552.html

大家都在问