rust-lang / rfcs

RFCs for changes to Rust
https://rust-lang.github.io/rfcs/
Apache License 2.0
5.89k stars 1.56k forks source link

Helpers for calling FFI functions with "compatible types" #892

Open alexcrichton opened 9 years ago

alexcrichton commented 9 years ago

It would be awesome if the std::ffi module contained utilities which serves as common conversions from Rust types to C types in FFI functions. For example in git2-rs I have a macro which will call a function but convert each argument to it's "C equivalent" before doing so.

The conversion trait is pretty ad-hoc at the moment, but it encompasses a number of useful conversions such as:

These sorts of conversions may not be appropriate for Rust at large, but the general idea is that types like Option<CString> are pretty painful to convert to a nullable pointer today:

let foo: Option<CString> = ...;
let ptr = foo.as_ref().map(|s| s.as_ptr()).unwrap_or(0 as *const _);

This issue is also motivated by rust-lang/rust#16035 because it would serve two purposes:

More broadly this sort of helper or trait plays into the story of writing unsafe code in Rust (and improving the ergonomics thereof) and may have other considerations. I'm sure there are also quite a few variants of the trait I've got already floating around in other crates as well :). Regardless, it would be nice to have a standard method of converting to a "C compatible" representation and perhaps even a nice convenient macro.

alexcrichton commented 9 years ago

cc @aturon

blaenk commented 9 years ago

Yeah, I also wrote macros in my bindings to do these conversions and it was a pain. I didn't think to create a trait like you did, so my macros got ugly. I definitely think that would be useful.

nagisa commented 9 years ago

This, or rather https://github.com/rust-lang/rust/issues/16035 must be fixed by beta, which suggests this RFC has to be approved and implemented in less than 3 days that’re left.