Search code examples
pythonpython-3.xctypes

Python ctypes structure: possible to be made without defining a class / inline?


Is it possible to pass an instance of a ctypes Structure to a library, without defining it as a class first? I have cases where I just need to instantiate each structure once, and pass a pointer to it to a dynamically loaded library, so it feels a bit... odd/unnecessary to have to make a class.


Solution

  • There doesn't seem to be anything built in, but you can define a function so most of the code doesn't have to make a class directly

    def make_struct(fields):
        class Struct(Structure):
            _fields_ = [(field_name, field_type) for (field_name, field_type, _) in fields]
        return Struct(*tuple(value for (_, _, value) in fields))
    

    with example usage

    my_struct = make_struct((
        ('my_first_field', c_int, 1),
        ('my_second_field', c_double, 1.0),
    ))
    

    (This is done at https://github.com/michalc/sqlite-s3-query/blob/main/sqlite_s3_query.py)