Skip to Content
Mastering Python
book

Mastering Python

by Rick Hattem
April 2016
Intermediate to advanced content levelIntermediate to advanced
486 pages
9h 21m
English
Packt Publishing
Content preview from Mastering Python

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Advanced Python Programming

Advanced Python Programming

Dr. Gabriele Lanaro, Quan Nguyen, Sakis Kasampalis
Getting Started with Python

Getting Started with Python

Fabrizio Romano, Benjamin Baka, Dusty Phillips
Python for Geeks

Python for Geeks

Muhammad Asif

Publisher Resources

ISBN: 9781785289729Supplemental Content