getditto / safer_ffi

Write safer FFI code in Rust without polluting it with unsafe code
http://getditto.github.io/safer_ffi
MIT License
925 stars 40 forks source link

Python example? #207

Open subalterngames opened 8 months ago

subalterngames commented 8 months ago

There is a test that generates a Python cffi. Is there an example of how to actually use this file?

Ronnbreizh commented 7 months ago

Hi, I wrote the Python CFFI plugin for safer_ffi when I was working with @danielhenrymantilla. You can find the package dittoffi on Pypi which uses the files generated by safer-ffi. Notably, you should pay attention to the _ffi_build.py file, which includes most of the CFFI logic. Here is an excerpt :


from cffi import FFI
ffi = FFI()

# Mostly company internal logic to fetch the correct lib and read the headers 

async def prepare_compilation():
    with read_header_file("dittoffi.cffi") as content:
        ffi.cdef(content)

    with read_header_file("dittoffi.h") as content:
        ffi.set_source("_ffi", content,
            library_dirs = [await find_ditto_path()],
            libraries = ['dittoffi']
        )

asyncio.run(prepare_compilation())

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

Finally, beware that the build instructions are splitted between the pyproject.toml and the setup.py file due to some CFFI shenanigans.