0

I am trying to pass a Numpy array into C, but get different results in Windows and Linux.

In 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]);
}

When I run the program in Windows, the output is "0 1 0 0 1 0 0 1 0", it works well.

But in Linux, the output is "0 0 1 0 0 0 0 0 1", why?

1 Answer 1

2

First, don't use numpy.int. It's just int, not any sort of NumPy thing. I think it's there for backward compatibility.

NumPy converts Python ints to dtype numpy.int_ (note the underscore) by default, and numpy.int_ corresponds to C long, not C int. Your code thus only works when C int and long are the same size, which they are on Windows, but not Linux.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.