I have:
let mut x = 0.0_f32;
I am dealing with C FFI, so I need to construct a
let y: *mut f32 = ...
How do I construct this y that points to x? (The C FFI function that takes a pointer to a f32 and writes the result there.)
I have:
let mut x = 0.0_f32;
I am dealing with C FFI, so I need to construct a
let y: *mut f32 = ...
How do I construct this y that points to x? (The C FFI function that takes a pointer to a f32 and writes the result there.)
You can coerce a mutable reference (&mut f32
) into a raw pointer (*mut f32
):
let y: *mut f32 = &mut x;
let y = &mut x as *mut f32
should do the trick
As general rule, try to minimize the number of "as" casts in your code. So mbrubeck solution seems better
That's fair. Though if it were me I would just let the reference coerce at the function call site instead of making a separate variable at all. i.e.
unsafe extern "C" fn takes_a_raw_pointer(ptr: *mut f32) {
*ptr = 42.;
}
fn main() {
let mut x = 0.0_f32;
unsafe {
takes_a_raw_pointer(&mut x); // automagically coerces here
}
println!("{}", x); // prints 42
}
Thanks @mbrubeck , @FenrirWolf , @leonardo ...
after reading the solutions, I figured out what I was doing wrong:
(& x) as *mut f32
I was taking a read-only ref instead of a mutable ref, and trying to cast it to a *mut f32. LOL.
PS: I also agree with @FenrirWolf 's appraoch of "use as *mut f32
directly at call site" -- seems to be how FFI is often handled.