MatthieuDartiailh / pyclibrary

C parser and ctypes automation for python
http://pyclibrary.readthedocs.org
MIT License
66 stars 29 forks source link

conversion to ctype and then numpy.dtype #50

Open maxlem opened 3 years ago

maxlem commented 3 years ago

Hi, I'm using your library to parse a file with structs definitions and generate the according numpy (structured) dtype.

from pyclibrary import CParser
import numpy as np
import ctypes

def to_dtype(name, type):
    s = type[0]
    n = 0
    if s.endswith("_t"):
        s = s[:-2]
    ctype = getattr(ctypes, f"c_{s}")
    if len(type) > 1:
        return (name, ctype, type[1][0])
    return (name, ctype)

[...]
        parser = CParser(["example_c_struct.h"])
        np_types = {}

        for (name, s) in parser.defs['structs'].items():
            members = s['members']
            np_type = np.dtype([to_dtype(name, type) for (name, type, default_Value) in members])
            np_types[name] = np_type

example_c_struct.h

#include <stdint.h>

struct ExampleCStruct{
    uint8_t u8;
    uint16_t u16;
    uint32_t u32;
    uint64_t u64;
    float flt;
    double dbl;
    char string[12];
};

So first I get the C language typestring, then I hackishly convert it to a ctype, and then I use the collection of ctypes to generate a numpy dtype.

Is there a cleaner way to get the ctype?