# Tag Archives: CFFI

One of the main downsides of writing applications in Python is that they can run slow. When you run into an insurmountable runtime speed issue the commonly accepted wisdom is to either use a more efficient Python implementation such as PyPy or to write the performance critical code in a more efficient compiled language (usually C or C++).

In this article I’m going to focus on ways to integrate fast compiled code for use by Python code, I usually make a point of consider the feasibility of PyPy vs the costs of using a different implementation as it can give you great performance increases with less added complexity.

If you want to use C or C++ compiled code in your Python project here’s a quick summary of the options available to you:

# Examples

A good way to demonstrate some of these options is via a simple example.

Lets say we want to compute a factorial recursively and we are using a fairly naive recursive approach. (Note that function calls in Python are slow which is a non-accidental part of this example, sometimes we could choose a better algorithm, but from the point of view of an example this is a fairly simple function where choosing a better language implementation would result in a win.)

Here’s the python code equivalent:

```def factorial(n):
"""Compute a factorial of n"""
if n <= 0:
return 1
else:
return n * factorial(n - 1)```

## Use the Python C interface

If you are using the cPython implementation you can use the C interface to call out to C code. Here’s an example:

```#include <Python.h>

/* Computes the factorial value we need for the example */
int
compute_it(int x){
if(x <= 0){
return 1;
}else{
return compute_it(x - 1) * x;
}
}

/* Python binding for our compute_it function */
static PyObject *
expensive_computations_compute_it(PyObject *self, PyObject *args){
int input, result;

if(!PyArg_ParseTuple(args, "i", &input)){
return NULL;
}
result = compute_it(input);
return Py_BuildValue("i", result);
}

/* Methods for our expensive_computations object*/
static PyMethodDef ExpensiveComputationMethods[] = {
{"compute_it", expensive_computations_compute_it, METH_VARARGS, "Computes our test factorial function"},
{NULL, NULL, 0, NULL} /* End of methods sential value */
};

/* define the module */
static struct PyModuleDef expensive_computations_module = {
"demo_module",
-1,
ExpensiveComputationMethods
};

/* Init code */
PyMODINIT_FUNC
PyInit_demo_module(void){
return PyModule_Create(&expensive_computations_module);
}

int main(int argv, char* argc[]){
/*Init the python interpreter */
Py_Initialize();

return 0;
}
```

Note that if your use case is just calling C library functions or system calls this is a poor choice, if you aren’t writing any custom code CFFI is a lot better in that case (not to mention more portable). One other thing that is worth mentioning is that there’s a lot of boilerplate here to convert between Python and C types. This is something that is handled better with some of the other libraries.

## Interface Python with C++

Previously the easiest way to do this was with Boost.Python as the library greatly reduced the boilerplate. However boost is a huge dependency to introduce to a project and can be a massive pain to compile. (This is a fairly substantial downside if you weren’t already using boost with your c++ code.) Thankfully there’s another option now that lets you get interoperability without introducing a heavy dependency on boost: pybind11

This library is header only which makes it much easier to compile as part of your c++ project.See the pybind11 tutorial on here for more about using this option.

Roughly it will look like this:

```#include <vector>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
namespace py = pybind11;
/**
* computes factorials
* @param n   The input number
*/
int compute_factorial(int n){
if(x <= 0){
return 1;
}else{
return compute_factorial(x - 1) * x;
}
}

/**
* Generate the python bindings for this C++ function
*/
PYBIND11_PLUGIN(factorials_example) {
py::module m("factorial_example", "Computing factorials in c++ with python bindings using pybind11");
m.def("factorial_from_cpp", &compute_factorial, "A function which computes factorials in C++");
return m.ptr();
}```

## Use CFFI

This is one of the biggest contributions from the PyPy ecosystem to the broader Python universe, it works on PyPy and cPython. The main idea behind CFFI is to generate an API to the C code without needing to worry about ABI issues. This gives you a rather large amount of efficiency in writing the code because a lot of the nasty details are hidden away from you. If you only need to make a call to existing C you don’t even need a C compiler run as part of the process, CFFI takes care of that for you.

Essentially you can write out your C code from within Python and CFFI will then go and compile the code and automatically create an API for you to use the C code from within Python. Honestly the whole idea is brilliant as it cuts down the time and effort required to consume existing C code. It also makes porting your code between different python implementations substantially easier because you don’t end up tied to the implementation specific way of creating extensions. You still need a C compiler and there’s a few limitations but overall this approach tends to work well. Going with the factorial example again it looks something like this:

```# file "cffi_factorials.py"

from cffi import FFI
ffibuilder = FFI()

ffibuilder.cdef("int factorial_fast(int);")

ffibuilder.set_source("_example",
r"""
static int factorial_fast(int n){
if(x <= 0){
return 1;
}else{
return compute_it(x - 1) * x;
}
}
""")

if __name__ == "__main__":
ffibuilder.compile(verbose=True)```

We then need to deal with actually building this as part of our build script because we need to call the C compiler to build our code before we can call it from python.

```# file "setup.py"
from setuptools import setup

setup(
...
setup_requires=["cffi>=1.0.0"],
cffi_modules=["cffi_factorials.py:ffibuilder"],
install_requires=["cffi>=1.0.0"],
)```

As you can see this is much less verbose in the code than using the python C interface.

## Embedding Python in another language

If the majority of your project is in another language but you need some sort of scripting ability embedding Python into your project can be a good option. This can be substantially easier overall than needing to write an interpreter in the main language. This is more of a high level decision but might be the right way for your project depending on what you are doing.

Some of my Python projects rely on a variety of packages, most of which install flawlessly via PIP. Recently I’ve been setting up a new machine running Ubuntu 16.04 and I ran into a few issues installing CFFI via PIP. Essentially CFFI requires some packages that are not installed by default on Ubuntu 16.04, the following should help you get past those issues.

When running `pip install cffi` the first failure you might see is something like this:

```building '_cffi_backend' extension
creating build/temp.linux-x86_64-3.5
creating build/temp.linux-x86_64-3.5/c
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -DUSE__THREAD -I/usr/include/ffi -I/usr/include/libffi -I/usr/include/python3.5m -I/home/janis/.virtualenvs/virt_env/include/python3.5m -c c/_cffi_backend.c -o build/temp.linux-x86_64-3.5/c/_cffi_backend.o
c/_cffi_backend.c:2:20: fatal error: Python.h: No such file or directory
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

----------------------------------------
Failed building wheel for cffi
```

This happens because Python development headers are not installed (as hinted at by the missing Python.h include file), to fix that we must install:

`sudo apt-get install python3-dev`

Or if for some reason you are running Python2 and the packages were not already installed:

`sudo apt-get install python-dev`

After installing that there’s a second fail you might encounter:

```running build_ext
building '_cffi_backend' extension
creating build/temp.linux-x86_64-3.5
creating build/temp.linux-x86_64-3.5/c
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -DUSE__THREAD -I/usr/include/ffi -I/usr/include/libffi -I/usr/include/python3.5m -I/home/janis/.virtualenvs/virt_env/include/python3.5m -c c/_cffi_backend.c -o build/temp.linux-x86_64-3.5/c/_cffi_backend.o
c/_cffi_backend.c:13:17: fatal error: ffi.h: No such file or directory
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

```

This is again a result of missing packages, this time libffi-dev:

`sudo apt-get install libffi-dev`

After installing that I got a successful CFFI install via PIP.