I want to pass a 2d numpy array to a function written in C using ctypes. When I try to access the data in the C function I get: Segmentation fault (core dumped). The code is:
code in C
#include <stdio.h>
void np_array_complex_shape(double ** data, int * shape){
printf("%d\n", shape[0]);
printf("%d\n", shape[1]); // These print ok.
printf("%f", data[0][0]); // This one throws: Segmentation fault (core dumped)
}
code in python:
import os
import ctypes
import numpy as np
import numpy.ctypeslib as npct
test_library_file_location = "library.so"
array_2d_double = npct.ndpointer(dtype=np.double, ndim=2, flags='CONTIGUOUS')
array_1d_int = npct.ndpointer(dtype=np.int32, ndim=1, flags='CONTIGUOUS')
LIBC = ctypes.CDLL(test_library_file_location)
LIBC.np_array_complex_shape.restype = None
LIBC.np_array_complex_shape.argtypes = [array_2d_double, array_1d_int]
x = np.array([[1,2,3],[4,5,6],[7,8,9]], dtype=np.float64)
s = np.array(x.shape, dtype=np.int32)
c = LIBC.np_array_complex_shape(x, s)
I've tried different solutions I found on line, but non work. Could someone help me?
I am using linux and gcc compilers.
double *.double **corresponds to indirect memory layout which is not supported by numpy. For more information see buffer-protocol: docs.python.org/3/c-api/buffer.html#buffer-structure