Search code examples
pythoncarraysparsinglibclang

Parse C Array Size with Python & LibClang


I am currently using Python to parse a C file using LibClang. I've encountered a problem while reading a C-array which size is defined by a define-directive-variable.

With node.get_children i can perfectly read the following array:

int myarray[20][30][10];

As soon as the array size is replaced with a variable, the array won't be read correctly. The following array code can't be read.

#define MAX 60;
int myarray[MAX][30][10];

Actually the parser stops at MAX and in the dump there is the error: invalid sloc.

How can I solve this?

Thanks


Solution

  • Run the code through a C preprocessor before trying to parse it. That will cause all preprocessor-symbols to be replaced by their values, i.e. your [MAX] will become [60].

    Note that C code can also do this:

    const int three[] = { 1, 2, 3 };
    

    i.e. let the compiler deduce the length of the array from the number of initializer values given.

    Or, from C99, even this:

    const int hundred[] = { [99] = 4711 };
    

    So a naive approach might still break, but I don't know anything about the capabilities of the parser you're using, of course.