Inspired by Carol Goulding's talk on "Rust Out Your C" and an article I read on porting C to Rust function by function.
If I have a program consisting of 3 functions called one after another:
1 (C) --> 2 (C) --> 3 (C)
And replace the second function as a statically linked, Rust function so the flow becomes:
1 (C) --> 2 (R) --> 3 (C)
Is the code in function 2, now memory and / or type safe? Does it gain any additional, beneficial properties in terms of safety?
Yes. And no. It depends.
First of, the C code in functions 1 and 3 will not be affected in any way, and will be just as unsafe (per Rust's definition as unsafe) as any C.
The code in function 2 will however benefit from Rust safety. Its implementation can be considered safer.
However, you'll need some glue between your C and Rust. Rust safety mostly come from its type system, and C type system is quite poor in comparison. You'll need to properly call your Rust function from your C function and C function from your Rust function. C is mostly unaware of Rust, so this needs to be done on the Rust side. While there are tools and crates to help with FFI, you always have to assume at some point that the C is correct, as a bug in the C could manifest even in (safe) Rust. Moreover calling a C function from Rust always requires
unsafe
, and a Rust function called from C will often have someunsafe
too. FFI is easy to get wrong: Wrong size of parameters, bad alignments, bad ABI, use of freed memory are all more likely at a language barrier and are all very unsafe.