Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

conversion to ctype and then numpy.dtype #50

Open
maxlem opened this issue May 16, 2021 · 0 comments
Open

conversion to ctype and then numpy.dtype #50

maxlem opened this issue May 16, 2021 · 0 comments

Comments

@maxlem
Copy link

maxlem commented May 16, 2021

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant