Hello I am trying to write a simple C function that takes two inputs (m,n) and creates a 2D - array of pointers. Now I want to call that function in Ctypes
and create a numpy array
from the pointers. I am however not sure how to proceed - and run into an error when calling the np.frombuffer
- function. Any help is apprechiated
c- file
#include <stdio.h>
#include <stdlib.h>
#define RANDOM_RANGE 50
typedef struct {
float val;
} cell;
cell **matrixMake(int m, int n){
// the rows
cell **pRow = (cell **)malloc(m* sizeof(cell *));
// the cols
for (int i = 0; i < m; i++){
pRow[i] = (cell *)malloc(n * sizeof(cell));
}
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
pRow[i][j].val = (float) (rand() % RANDOM_RANGE);
}
}
return pRow;
}
Corresponding Python File
import numpy as np
from numpy.ctypeslib import ndpointer
from ctypes import *
class CELL(Structure):
_fields_ = [ ('val', c_float) ]
libc = CDLL("c_arr_multi.so")
libc.matrixMake.argtypes = [ c_int, c_int ]
libc.matrixMake.restype = POINTER(POINTER(CELL))
res = libc.matrixMake(6, 3)
x = np.frombuffer((c_float * 6 * 3).from_address(libc.matrixMake(6, 3)), np.float32).copy()
print(x)
I am simply not shure how to proceed