0

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

5
  • I only have a passing knowledge of C, but it looks like you've defined a 2d array by starting with an array of pointers, each which is itself an array (of pointers or values). That structure is more like a Python nested list. numpy has one C databuffer with all values (not pointers), and shape (and strides) tuples that control how its methods iterate through those values. Commented Mar 26, 2021 at 1:42
  • Thanks for the answer. Hmm would you simply loop through the nested array and populate a numpy array then? I am also just a beginner, but that seems somewhat inefficient to me. Commented Mar 26, 2021 at 2:10
  • Maybe Python expects a 2D array? A pointer table isn't a 2D array, it is a method of emulating a 2D array for the sole purpose of making your program needlessly slow. See Correctly allocating multi-dimensional arrays. Commented Mar 26, 2021 at 8:54
  • 1
    @baconStrips It's in fact more efficient to have a single contiguous buffer than a buffer of pointers in which each pointer points to other buffers scattered though memory. Commented Mar 26, 2021 at 17:43

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.