0

I am currently learning how to call a C library from Python. I do not quite understand the proper way to pass an array from Python to a C function for computation and get the returned value back to Python.

Suppose that I have a C function, namely cfun, which takes an integer, dim, and an array, double *a, for computation and return the results to another array, double *b. In my Python routine, I have declared two arrays, arr1 and arr2 and I would like to tell the cfun to use the actual locations of the allocated memory of arr1 and arr2 for computation.

Is my *.pyx code which is shown below efficient enough for my purpose, whereas cfun is computationally expensive and is frequently called?

import numpy as np
cimport numpy as np

cdef extern from "header.h": 
    void cfun ( int dim, double *a, double *b ) 

def pyfun ( dim, np.ndarray[double,ndim=1] arr1, np.ndarray[double,ndim=1] arr2 )

    cfun ( dim, <double*> arr1.data, <double*> arr2.data )
    return None
Jens
  • 69,818
  • 15
  • 125
  • 179
Juan
  • 21
  • 3
  • 1
    https://gist.github.com/lmammino/10ae9ad290809f172e6eb3b6957bd18c This github page may help. It shows a simple example of how to run a C function with parameters called by python and then return the result to python – mrblue6 Feb 14 '23 at 17:54
  • 1
    There are many examples, here are a couple that partially achieve what you;re after: [\[SO\]: Problem in passing numpy array to a C function (@CristiFati's answer)](https://stackoverflow.com/a/70634363/4788546), [\[SO\]: What is numpy.ctypeslib.as\_ctypes exacty doing (@CristiFati's answer)](https://stackoverflow.com/a/68505437/4788546), [\[SO\]: Boundary problems using a numpy kernel and padding on a matrix within a C functions called from python (@CristiFati's answer)](https://stackoverflow.com/a/74174207/4788546). – CristiFati Feb 14 '23 at 18:08
  • Python does not have a built-in array type. Did you mean that you have **lists**? Or were you talking about the standard library `array.array`, or a Numpy array, or something else? – Karl Knechtel Feb 14 '23 at 18:11

0 Answers0