FFI with header-only code

Hey there,

I am writing FFI bindings to a C library that contains some functions defined in the header file. Some of these functions themselves make use of preprocessor macros which ultimately generate platform specific asm in some cases, implementing atomic synchronizations I'd rather not have to understand. So I'd rather not rewrite at least some of these functions in Rust.

What is the best way to write linkable FFI bindings to these functions? It has occurred to me that I could create a new c project which essentially re-exports them, is that the only reasonable way?

1 Like

Rather than making a full C project, you may just be able to make a little shim file and compile it in your build script with https://docs.rs/cc/1.0.46/cc/.


Yea that seems like the easiest thing to do. Thanks!

That suggestions sounds better than my strategy of unwrapping the macros and calling the root functions by hand. Can you post back if you find this to be easy?

It seems very maintainable, even as someone who is usually flustered by all the moving parts in FFI.

I just added a .c file to my project root, wrote a build script with a rather straightforward invocation of the cc crate, and added an additional extern block for my new object. Not too bad.

1 Like