Monday, 12 December 2022

Load c_char_p_Array in a Numpy array

Consider a C buffer of N elements created with:

from ctypes import byref, c_double

N = 3
buffer = (c_double * N)()
# C++ function that fills the buffer byref
function(byref(buffer))
# load buffer in numpy
data = np.frombuffer(buffer, dtype=c_double)

Works great. But my issue is that the dtype may be numerical (float, double, int8, ...) or string.

from ctypes import byref, c_char_p

N = 3
buffer = (c_char_p * N)()
# C++ function that fills the buffer byref
function(byref(buffer))
# Load in.. a list?
data = [v.decode("utf-8") for v in buffer]

How can I load those UTF-8 encoded string directly in a numpy array? np.char.decode seems to be a good candidate, but I can't figure out how to use it. np.char.decode(np.frombuffer(buffer, dtype=np.bytes_)) is failing with ValueError: itemsize cannot be zero in type.



from Load c_char_p_Array in a Numpy array

No comments:

Post a Comment