Andreas Flöjt
Andreas Flöjt

Reputation: 349

What's the purpose of writing bindings for C libraries for Rust?

I was under the impression that bindings are intermediate layers you write so that you may use a library written in one language in an application written in another. It seems that Rust may call C with zero overhead

For a concrete example, Vulkan is a C API, yet people are working on bindings for Vulkan (1, 2, 3).

If C can be called directly from Rust, why would you want to create bindings? Have I misunderstood something?

Upvotes: 11

Views: 5985

Answers (1)

Lukas Kalbertodt
Lukas Kalbertodt

Reputation: 88556

While Rust can call C functions without overhead, the Rust compiler still needs to know about the existence of those functions. To tell the compiler you have to declare those functions in an extern "C" { .. } block. You can read more about the topic in the FFI chapter of the Rust book. For C functions that are used by many people (e.g. Vulkan), it makes sense to put all those declarations into a Rust library that others can just use, instead of writing the bindings themselves.

With the bindings mentioned above we simply expose the original C interface to the Rust programmer. But most Rust programmers rather want to use an API that is idiomatic in Rust (we call it "rusty"). That is: using high level concepts of Rust, like traits and closures, and being "safe".

The Vulkan libraries you linked:

  • The second link is just is a raw binding generated with a tool (rust-bindgen).

  • The purpose of tomaka's library is to create a rusty API, so it isn't just a collection of function declarations. tomaka chooses to introduce very little overhead in order to create a library that most Rust programmers are more comfortable to use than the C interface. (by the way: tomaka did this for OpenGL, too).

  • I don't really know about the first library you linked, but I think it's something in between the two approaches above.

Upvotes: 13

Related Questions