Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to do Vec<String>? #972

Open
Masber opened this issue Jun 2, 2024 · 0 comments
Open

How to do Vec<String>? #972

Masber opened this issue Jun 2, 2024 · 0 comments

Comments

@Masber
Copy link

Masber commented Jun 2, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant