1

I'm having an issue passing a Numpy ndarray of integers to a C function via ctypes. Below is a MWE that shows the problem. First the C function, it just takes an array as an argument prints its values.

#include <stdio.h>

void my_fun(int *array, int num)
{
    for(int i=0; i<num; i++){
        printf("array value: %d \n", array[i]);
    }
}

Now the Python/ctypes implementation:

import numpy as np
import ctypes

c_int_p = ctypes.POINTER(ctypes.c_int)

_sample_lib = np.ctypeslib.load_library('_sample','.')
_sample_lib.my_fun.restype= None
_sample_lib.my_fun.argtypes = [c_int_p, ctypes.c_int]

my_array = np.arange(5,dtype=np.int)

_sample_lib.my_fun(my_array.ctypes.data_as(c_int_p), len(my_array))

Running the Python code produces:

array value: 0
array value: 0
array value: 1
array value: 0
array value: 2

Notice the extra 0's in the array. Why are they there and how do I get rid of them?

2
  • possible duplicate of python ctypes - passing array - odd output Commented Mar 10, 2014 at 3:49
  • Yes, it is. Thanks for the link, I could not find it even though I figured this had been addressed. Commented Mar 10, 2014 at 3:56

0

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.