ihciah / rust2go

Call Golang from Rust
https://en.ihcblog.com/rust2go/
Other
48 stars 10 forks source link

Weird bug without `#[repr(C)]` #4

Closed cxw620 closed 2 months ago

cxw620 commented 2 months ago

According to offcial example, we should add rust2go::R2G attribute to structs that will be passed to Go side.

#[derive(Debug, rust2go::R2G)]
pub struct Http2SettingFfi {
    pub setting_id: u16,
    pub setting_val: u32,
}

However, when it comes to the example above, there will come a weird bug that Go side will exchange, well I wonder if I explain clearly, values of these two fields.

After thinking for a while, I come to the solution. It's simple: don't forget #[repr(C)], which assures that the order, size, and alignment of fields is exactly what you would expect from C that acting as FFI bridge between Rust and Go.

#[derive(Debug, rust2go::R2G)]
#[repr(C)]
pub struct Http2SettingFfi {
    pub setting_id: u16,
    pub setting_val: u32,
}

BTW, I also want to share my experience here: if you pass a string from Rust to Go, you'd better make a deep copy especially when it acts like config, etc, otherwise if original one is dropped within Rust side, you may encounter with unfarished behaviors.