I’m trying to utilize a C library using ctypes in Python. The C library provides a subroutine that returns two arrays via pointers: one for integer data and one for float data.
Here’s a simplified example of my Python code:
import ctypes
import numpy as np
lib = ctypes.CDLL('./reader.so') # Assicurati di sostituire con il percorso corretto della tua libreria
readdata = lib.readdata
readdata.argtypes = [ctypes.POINTER(ctypes.POINTER(ctypes.c_int)), ctypes.POINTER(ctypes.POINTER(ctypes.c_float))]
data_ptr = ctypes.POINTER(ctypes.c_int)()
xyz_ptr = ctypes.POINTER(ctypes.c_float)()
readdata(ctypes.byref(data_ptr), ctypes.byref(xyz_ptr))
size = 17 # Dimensione dell'array
data = np.frombuffer((ctypes.c_int * size).from_address(ctypes.addressof(data_ptr.contents)), dtype=np.int32)
xyz = np.frombuffer((ctypes.c_float * size).from_address(ctypes.addressof(xyz_ptr.contents)), dtype=np.float32)
print("Dati integer:", data)
print("Dati float:", xyz)
libc = ctypes.CDLL(None)
libc.free(data_ptr)
This is the code of the fortran module (reader.so):
subroutine readdata(data1, data2) bind(c, name='readdata')
use iso_c_binding
implicit none
integer(c_int), intent(out), dimension(:), allocatable :: data1
real(c_float), intent(out), dimension(:), allocatable :: data2
integer :: length, i
length = 17 ! Esempio di dimensione, sostituire con la dimensione effettiva
allocate(data1(length))
allocate(data2(length))
! Assegna dati casuali all'array di interi data1
do i = 1, length
data1(i) = i * 10 ! Modifica questo assegnamento con la logica desiderata
end do
! Assegna dati casuali all'array di float data2
do i = 1, length
data2(i) = real(i * 10, kind=4)
end do
end subroutine readdata
The problem is that I’m encountering an error when trying to convert the pointers into numpy arrays. I suspect that the pointers might be close to each other and may cause memory overlap issues.
I’ve tried rearranging the operations and manually deallocating memory, but I haven’t been able to resolve the issue.
Could someone help me understand how to properly solve this problem of converting C pointers to numpy arrays in Python?
Thank you in advance for any assistance!
Michael Leanza is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.