mystor / rust-cpp

Embed C++ directly inside your rust code!
Apache License 2.0
802 stars 44 forks source link

Allow annotating Rust types in cpp! macro (or just allow arbitrary expressions) #25

Open uzytkownik opened 7 years ago

uzytkownik commented 7 years ago

I'm noticing that 99% of my errors are type errors during calling cpp! macro:

// Handle
struct Wrap {
    ptr: ::libc::c_void
}
pub fn test(wrap: &mut Wrap) {
    cpp!([wrap as "Wrap *"] {
        wrap->test();
    });
}

This compiles but segfaults. Correct way is:

// Handle
struct Wrap {
    ptr: ::libc::c_void
}
pub fn test(wrap: &mut Wrap) {
    let wrap_ptr = wrap.ptr;
    cpp!([wrap_ptr as "Wrap *"] {
        wrap_ptr->test();
    });
}

My code is littered with _ptr variables and other casting. It might be nice to have following syntax:

// Handle
struct Wrap {
    ptr: ::libc::c_void
}
pub fn test(wrap: &mut Wrap) {
    cpp!([(wrap.ptr  as ::libc::c_void) as "Wrap *"] {
        wrap->test();
    });
}

Thus avoiding temporary variables and making code more type safe (if we type by accident wrap : ::libc::c_void it will cause type error. Note that mutability should still work, only with slightly different syntax:

let y: i32 = 10;
let mut z: i32 = 20;
let x: i32 = cpp!([y as "int32_t", &mut z as "int32_t &"] -> i32 as "int32_t" {
    z++;
    return y + z;
});