1

I want to use numpy C array api (https://numpy.org/doc/stable/reference/c-api/array.html) using ctypes python library. Similarly to how I can use python c api with ctypes. For example, I can reference PyLong_FromLong function like this:

ctypes.pythonapi.PyLong_FromLong

Is this possible to do? Is there some compiled .so file that I can load like this

np_api = ctypes.CDLL(file_path)

to be able to use numpy api?

Gleb
  • 33
  • 3
  • Does this answer your question? [How to use NumPy array with ctypes?](https://stackoverflow.com/questions/3195660/how-to-use-numpy-array-with-ctypes) or [How can I return a multidimensional array from a shared library in C to python as an np.array?](https://stackoverflow.com/questions/71195319/how-can-i-return-a-multidimensional-array-from-a-shared-library-in-c-to-python-a/71197327) or even [How to convert a ctypes array of c_uint to a numpy array](https://stackoverflow.com/questions/57682751/how-to-convert-a-ctypes-array-of-c-uint-to-a-numpy-array) – Jérôme Richard May 29 '22 at 15:54
  • @JérômeRichard Not exactly. https://stackoverflow.com/questions/71195319/how-can-i-return-a-multidimensional-array-from-a-shared-library-in-c-to-python-a/71197327 your answer is very close, but it creates memory leakage. I actually want to pass ownership of data to numpy array so that there is no memory leakage. I thought that I can do this if I try to use Numpy C api directly. – Gleb May 29 '22 at 16:42
  • Did you read the `WARNING` note in the comments about freeing the memory? I remember this problem and using free solved it. AFAIK Numpy should not free the buffer because it does not know how it was allocated and there are many allocator. One could even return a pointer to a memory-mapped buffer (possibly owned by a remote process). Thus, AFAIK this is how the API works (which does not mean there is a leak). – Jérôme Richard May 29 '22 at 16:55
  • First of all one would ask why is this necessary, as from a technical point of view it makes no sense. *NumPy* *.dll*s export the extension module *API* so that this very scenario is avoided. – CristiFati Jun 01 '22 at 13:14

0 Answers0