Skip to content
Search

Python:cffi

lastmod 2024-01-08created 2021-12-063 edits

Example

Installation:

$ python3 -m pip install cffi

Linking a C library:

from cffi import FFI


ffibuilder = FFI()

ffibuilder.cdef("""
    double sqrt(double x);
""")

ffibuilder.set_source("_libmath",
    """
    #include <math.h>
    """,
    library_dirs = [],
    libraries = ['m']
)

ffibuilder.compile(verbose=True)

You must call ffibuilder.compile at the end to produce a shared library that Python can link.

Using the library:

from _libmath import lib

x = lib.sqrt(4.5)

print(F"The square root of 4.5 is {x}.")

See also

Favorite site

author Zer0 sitemap