I'd like to send a list of strings to a C function:
import ctypes
from ctypes import c_double, c_void_p, Structure, cast, c_size_t, POINTER
import numpy as np
class FFIArray(Structure):
"""
Convert sequence of structs or types to C-compatible void array
"""
_fields_ = [("data", c_void_p),
("len", c_size_t)]
@classmethod
def from_param(cls, seq):
""" Allow implicit conversions """
return seq if isinstance(seq, cls) else cls(seq)
def __init__(self, seq, data_type):
array = np.ctypeslib.as_array((data_type * len(seq))(*seq))
self._buffer = array.data
self.data = cast(
array.ctypes.data_as(POINTER(data_type)),
c_void_p
)
self.len = len(array)
This works for e.g. c_double, but fails when I try it with c_char_p, with the following error:
ValueError: '<z' is not a valid PEP 3118 buffer format string
Is there a better way to do this? I'm also not wedded to using numpy, although it's useful for converting iterables of numeric types and numpy arrays to _FFIArray elsewhere.
from Numpy error when converting array of ctypes types to void pointer
No comments:
Post a Comment