convert triply-nested array to void pointer using ctypes

sth urschrei at gmail.com
Wed Aug 24 05:29:07 EDT 2016


I'd like to send an array containing arrays of 2-element float arrays to a foreign function, as the following struct:

class _FFIArray(Structure):
    _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):
        self.data = cast(
            np.array(seq, dtype=np.float64).ctypes.data_as(POINTER(c_double)),
            c_void_p
        )
        self.len = len(seq)

This works for data such as [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], … ], (.shape is n, 2 where n is an arbitrary length) but I'd like it to work for data such as

[
    [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], … ],
    [[7.0, 8.0], [9.0, 10.0], [11.0, 12.0], … ],
    …
]

which has .shape p, q, 2 where p and q are of arbitrary length.

Is this possible?




More information about the Python-list mailing list