python-cffi/cffi

Getting function types without loading the corresponding library

Closed this issue · 3 comments

Hi, Is there a way to get the type of a function declared in an FFI.cdef call without compiling and loading the implementation?

I'm looking into using cffi to generate ctypes bindings for a shared library based on its header file, and I want to avoid having to load the library once with cffi and then again with ctypes. (I'm opting to use ctypes over cffi because ctypes structure types can be used as data types for NumPy arrays.)

ffi = cffi.FFI()
ffi.cdef(c_header_text)
lib = ffi.dlopen(None)

ffi.list_types() # Requesting type information works
dir(lib) # Listing macro and function names works
lib.SOME_MACRO # Requesting macro values works
lib.some_function # Requesting functions results in an undefined symbol error

Thanks for the response! That's good to know the library won't be loaded twice.

I'm not particularly worried about performance, but if there was a way to use cffi such that the part of the code generating the bindings didn't need to be passed all the details of how to compile the library, that would still be nice to know. It's maybe not the highest-stakes issue, but I like the conceptual clarity of "header text in -> wrapper objects out", and if I spin the little binding generation module I wrote this afternoon out into a script, it would be nice if I could auto-run it whenever the header file is edited, without having to recompile the library (which can take a little while).

There is no built-in way to do that, but you can write a Makefile or integrate the "run the binding generation script" step into some other build system you might already have, or even write some hack in your main program that first checks if some header files were modified, automatically execute the binding generation script if so, and only then loads the generated code/data.