Casting struct pointer to *const f32

I have a struct representing a Vector which I need to pass to a c function. The c function takes a pointer to an f32 (well, a pointer to the first of three sequential f32's).

#[repr(C)]
pub struct Vector3 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

let v = Vector3 { x: 1, y: 2, z: 3 };

unsafe {
    my_c_function(&v as *const f32);
}

But the compiler complains that:

casting `&Vector3` as `*const f32` is invalid rustc(E0606)

How should I be doing this instead?

You need to do two casts,

&v as *const Vector3 as *const f32

Because you can't go directly from a reference to a pointer to a different type.

1 Like

Thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.