CFFI

The CFFI library offers options very similar to ctypes, but it's a bit more direct. Unlike the ctypes library, a C compiler is really a necessity for CFFI. With it comes the opportunity to directly call your C compiler in a very easy way:

>>> import cffi
>>> ffi = cffi.FFI()
>>> ffi.cdef('int printf(const char* format, ...);')
>>> libc = ffi.dlopen(None)
>>> arg = ffi.new('char[]', b'spam')
>>> libc.printf(arg)
4
spam>>>

Okay… so that looks a bit weird right? We had to define how the printf function looks and specify the arguments to printf with a valid C type declaration. Getting back to the declarations, however, instead of None to ffi.dlopen, you can also specify the library you wish to load. If you remember the ctypes.util.find_library ...

Get Mastering Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.