Equivalent of struct->ptr = (char*) data in rust

Viewed 73

There's the following line in C:

my_struct->ptr = (char*) data

where as you can see, my_struct has a ptr member of type char*

I have this on Rust:

struct MyStruct {
    ptr: *mut libc::c_char
}

then I fill it like this:

unsafe{*my_struct}.ptr = Box::into_raw(my_data) as *mut libc::c_char;
unsafe{((*my_struct).ptr as *mut MyData).as_mut()}.unwrap();

but I'm getting either an unwrap panic on the line above. See that I acessed it immeidately after setting it, so no lifetime, out of scope problems for this data.

Here's the actual MyStruct:

https://github.com/mysql/mysql-server/blob/8.0/include/mysql/udf_registration_types.h#L69

I think the problem is resumed here:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=293ca891bedb9528ae840bcdf737777c

or in other words:

#[derive(Clone, Copy)]
struct MyStruct {
    ptr: *mut libc::c_char
}

struct MyData{}

fn main() {
    let my_struct = &mut MyStruct{
        ptr: std::ptr::null_mut()
    } as *mut MyStruct;
    let my_data = Box::new(MyData{});
    unsafe{*my_struct}.ptr = Box::into_raw(my_data) as *mut libc::c_char;
    unsafe{((*my_struct).ptr as *mut MyData).as_mut()}.unwrap();
}
1 Answers

By doing unsafe{*my_struct}.ptr, you're copying *my_struct, then overwriting .ptr of that copy, which is why you're observing no change. Instead, write to (*my_struct).ptr:

unsafe {
    (*my_struct).ptr = Box::into_raw(my_data) as *mut libc::c_char;
}
Related