I have a C source/header file that are part of a bigger project. I would like to test this as a unit, independent of the real project. While it would be possible to do this in C by creating a new project with a different
// Implementation of magic.
int add(int a, int b)
// Add two numbers (where a + b is not greater than INT_MAX).
int add(int a, int b);
INCLUDE_DIRS = ('.',)
SOURCES = ('magic.c',)
ffi = cffi.FFI()
include_dirs = INCLUDE_DIRS,
sources = SOURCES,
libraries = ,
For a project of mine, I use
cffi to test my C code. IMHO
cffi is a great tool to generate python bindings for C code and therefore think that it is a reasonable tool to use for calling and testing C functions from python. However, your code will only be as cross platform as the C code is, since you have to compile the binding for every platform.
Below you can find a few references to the documentation that should answer your questions. Additionally I wrote some example code to illustrate how you would use
cffi. For a larger example, you can find my project at https://github.com/ntruessel/qcgc/tree/master/test.
The documentation for
set_source() can be found here https://cffi.readthedocs.io/en/latest/cdef.html
https://cffi.readthedocs.io/en/latest/overview.html explains how you can use CFFI, I recommend API, out-of-line.
Four your example,
build_magic_tests.py would look something like this:
from cffi import FFI ffibuilder = FFI() # For every function that you want to have a python binding, # specify its declaration here ffibuilder.cdef(""" int add(int a, int b); """) # Here go the sources, most likely only includes and additional functions if necessary ffibuilder.set_source("magic_tests", """ #include "magic.h" """, sources=["magic.c"]) if __name__ == "__main__": ffibuilder.compile()
To generate the magic_tests module, you have to run
python build_magic_tests.py. The generated module can be imported and used like this:
from magic_tests import ffi, lib def run_add(): assert 4 == lib.add(4, 5)