Is it possible to cast a type A reference to other raw pointer of type B if type A is not public?


#1

According to References and raw pointers, reference can coerce to raw pointers to the same type. There existed a situation that, the type is not public, so casting reference would generate a warning. I wonder in this situation, is it possible to transfer the type A reference to a type B raw pointer first, and then transfer type B raw pointer to type A pointer?

demo code:

struct A {
    pub x: i32, }

const GG: usize = 0x1000;

unsafe fn get_deref<T>(x: usize) -> &'static T {
    &*(x as *mut T)
}

pub fn get_ref() -> &'static A {
    unsafe { get_deref(GG) }
}


fn main() {
    let x = get_ref();

    let xx = x as *const A;
}


error[E0446]: private type `A` in public interface
  --> test.rs:10:1
   |
10 | / pub fn get_ref() -> &'static A {
11 | |     unsafe { get_deref(GG) }
12 | | }
   | |_^ can't leak private type

error: aborting due to previous error

#2

It’s possible. Any pointer can be casted to any other pointer type of same mutability. For instance.

let a_ref: &A;
a_ref as *const A as *const B as *const A

#3

Thanks @xfix, you are right.

struct A {x: i32,}
fn main() {
    let x: &A = &A{x: 1};
    let y = x as *const A as *const i32 as *const A;
}

The error of my code is originated from

pub fn get_ref() -> &'static A {
    unsafe { get_deref(GG) }
}

moving pub away, this error is solved.