trolldbois / ctypeslib

Generate python ctypes classes from C headers. Requires LLVM clang
http://trolldbois.blogspot.com/search?q=ctypeslib
MIT License
217 stars 61 forks source link

Can't tell if a char array is const or not #96

Open PedroAS7 opened 3 years ago

PedroAS7 commented 3 years ago

Hello all,

I'm working on a little personal project that takes the output from the clang parser, and outputs information, about the functions it found, on the console.

I was messing around with a function that has a parameter of type const char*, but I've noticed that I have no way of telling whether it is const or not, after it has been parsed.

What I'm trying to do

Here's an example of what I'm trying to do:

parser = Clang_Parser(flags=[])
lang = "c"
flags = []
parser.parse_string("""
                    void functionName (const char *xpText)
                    {
                        // Function code goes here
                    }
                    """, lang=lang, flags=flags)
items = parser.get_result()

What I expected to get

In the items list, I expected to see an item like this: image

In this item, I'm able to know if the argument is volatile and/or constant. Instead, I get something like this: image

Is there any way to know if the parameter is constant or not? From what I've found on cursorhandler.py, this information is not at all taken into account, and therefore the type CvQualifiedType is never used. I've also noticed that, in Clang's cindex.py, there is a function is_const_qualified in class Type that would allow us to is the element is const or not. Nevertheless, I don't see it referenced anywhere, and by the time I start parsing the output I get from the Clang parser, it is already too late to be able to call it.

Is there any other way I can use to know this?

Edit: I change a little bit how the fundamental types are handled on _handle_fundamental_types, on file typehandler.py (lines 37 on). This creates an instance of CvQualifiedType and sets the FundamentalType's instance in its typ variable.

def _handle_fundamental_types(self, typ):
    """
    Handles POD types nodes.
    see init_fundamental_types for the registration.
    """
    ctypesname = self.get_ctypes_name(typ.kind)
    if typ.kind == TypeKind.VOID:
        size = align = 1
    else:
        size = typ.get_size()
        align = typ.get_align()
    # Changed from here until the end of the function
    constant = typ.is_const_qualified()
    volatile = typ.is_volatile_qualified()
    ftype = typedesc.FundamentalType(ctypesname, size, align)

    if constant or volatile:
        return typedesc.CvQualifiedType(ftype, constant, volatile)

    return ftype