Search code examples
pythonpython-cffi

How can I get the `const` modifier of a CFFI function in Python?


I am writing a Python wrapper for generated C code, which contains functions that use pointer arguments as outputs. I want to introspect those functions, generated using CFFI, to determine if they are input our output arguments. The input arguments are marked const, but it seems CFFI discards this information.

Consider the following example

from cffi import FFI
ffibuilder = FFI()

ffibuilder.set_source("_example",
   r"""
        int add(const int a, const int b) {
            return a+b;
        }
    """)

ffibuilder.cdef("""
        int add(const int a, const int b);
""")

if __name__ == "__main__":
    ffibuilder.compile(verbose=True)
    import _example
    ff = _example.lib.add
    ff_t = _example.ffi.typeof(ff)
    print(ff_t)

Which prints <ctype 'int(*)(int, int)'>, while the inputs are defined const in the code.


Solution

  • Sorry, not possible. This info is discarded already when translating the parsed code to CFFI's internal ctype.

    Look at the pycparser module (which is the one that CFFI uses internally); it transforms C source code into a parse tree. From there you can get all this info again more directly.