mozilla / cbindgen

A project for generating C bindings from Rust code
Mozilla Public License 2.0
2.27k stars 294 forks source link

How to do Vec<String>? #972

Open Masber opened 1 month ago

Masber commented 1 month ago

Dear cbindgen community,

I am learning FFI/Rust and I am learning cbindgen, my goal is to optimize my Rust code in order to create the right header file.

For instance this is how I currently define my Rust/C structs to pass the pointer to a Vec and its length

#[repr(C)]
#[derive(Debug)]
pub struct MyStruct3 {
    data: *const *const c_char,
    length: c_int,
}

And here is how I am converting from Rust to C

    let c_string_vec = unsafe {
        let string_vec_data = (*c_data).data;
        let string_vec_length = c_data.length;
        std::slice::from_raw_parts(string_vec_data, string_vec_length as usize)
            .iter()
            .map(|&cstr| CStr::from_ptr(cstr).to_string_lossy().into_owned())
            .collect::<Vec<String>>()
    };

I would like to ask, if there is a better way/more idiomatic way to do this from cbindgen perspective?

thank you very much