import cffi ffi = cffi.FFI() lib = ffi.dlopen("libc.so.6") string = b"Hello, world!" length = lib.strlen(string) print(length)
import cffi ffi = cffi.FFI() ffi.cdef(""" struct person { char *name; int age; }; """) lib = ffi.dlopen("libexample.so") person = ffi.new("struct person*", {"name": b"John", "age": 30}) lib.print_person(person)
import cffi ffi = cffi.FFI() ffi.cdef(""" int add(int, int); """) lib = ffi.dlopen("libexample.so") def add(a, b): return lib.add(a, b)In this example, we use `cdef` to define a function called `add` that takes two integers and returns an integer. We then load a C library called `libexample.so` and define a Python function called `add` that calls the `add` function from the C library. We can then import this module into other Python code and use the `add` function as if it were a native Python function. In conclusion, cffi is a powerful tool for Python developers who need to interface with low-level C code. It allows for easy integration between Python and C, and can be used to define data structures, call functions, and even create Python modules that wrap C libraries.