rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
96.58k stars 12.48k forks source link

support for implementing "extern" functions required by C code when it's declared in a C header/rust-binding #58493

Open M1cha opened 5 years ago

M1cha commented 5 years ago

Some C libraries require the user of the lib to implement (platform/sys) functions which are then used by the lib.

The library header usually declares the function so you can implement it wherever you want and get a compiler error if the signature has changed and your implementation is thus wrong now.

If I use bindgen to generate rust bindings for such a library I'm unable to implement such functions using rust, because they already are declared as extern to rust and the compiler treats this as duplicate/mismatching implementations.

If I would just blacklist these functions in bindgen so they'd not be part of the generated bindings there'd be no check if my rust function's signature actually matches the one declared in the C header which is installed on the system.

I think the solution to this would be adding a new function-attribute which lets you explicitly implement an extern function in rust.

M1cha commented 4 years ago

I managed to do it like this:

pub trait T {
    extern fn hello_rust();
}

struct S;

impl T for S {
    #[no_mangle]
    extern fn hello_rust() {
    }
}

this way:

now I'll just have to find a way to make bindgen generate this trait for me.