Passing a set of NumPy arrays into C function for input and output

后端 未结 2 2191
[愿得一人]
[愿得一人] 2021-02-13 19:41

Let\'s assume we have a C function that takes a set of one or more input arrays, processes them, and writes its output into a set of output arrays. The signature looks as follow

2条回答
  •  一生所求
    2021-02-13 20:03

    To do this specifically with Numpy arrays, you could use:

    import numpy as np
    import ctypes
    
    count = 5
    size = 1000
    
    #create some arrays
    arrays = [np.arange(size,dtype="float32") for ii in range(count)] 
    
    #get ctypes handles
    ctypes_arrays = [np.ctypeslib.as_ctypes(array) for array in arrays]
    
    #Pack into pointer array
    pointer_ar = (ctypes.POINTER(C.c_float) * count)(*ctypes_arrays)
    
    ctypes.CDLL("./libfoo.so").foo(ctypes.c_int(count), pointer_ar, ctypes.c_int(size))
    

    Where the C side of things might look like:

    # function to multiply all arrays by 2
    void foo(int count, float** array, int size)
    {
       int ii,jj;
       for (ii=0;ii

提交回复
热议问题