Does Rust offer C interop?

One question, there is dwl which is a tiling window manager configured in C (like dwm but for wayland over x.org/x11, I wanted to know if Rust can interact with it via C interop? Is it difficult to achieve this?

Yes, it does. Here's a book on it: https://doc.rust-lang.org/nomicon/ffi.html

2 Likes

I took a look, does it have to be all unsafe code just to do C bindings?

Yes.

The Rust compiler can only do safety checking on Rust source code. It has no idea what goes on inside any C code you link into the system (Neither does the C compiler for that matter, it checks nothing much). Ergo any such linkage must be "unsafe".

Think of it like this: When Rust passes control to C it's like you jumping into a pit full of vipers in the hope that none of them bites you. I might put up a sign "unsafe, vipers in pit".

12 Likes

The typical strategy when doing C interop with Rust is to write a crate with a -sys suffix that contains raw unsafe bindings to the C code such as dlw-sys, and then you would make a crate called just dlw that would provide a 100% safe interactions that are built on top of dlw-sys. There are also project such as cbindgen that will help automatically generate the dlw-sys crate for you.

For example you have the openssl-sys crate which is 100% unsafe and raw bindings to libopenssl, but then you have the openssl crate which is all safe Rust that implements a safe way to use OpenSSL, but it calls the unsafe functions in openssl-sys to do its work.

I would say it isn't super difficult to do, but it does require understanding how to use the C interface. Just like you would need to know how to use the API if you were using C.

Well, I guess, depending on the circumstance, as people have said before, unsafe Rust is actually harder than C to get right, but I don't know if it is much harder in the context of FFI.

1 Like