Skip to content

Cannot get a 'static reference to an explicit memory location #18267

Closed
@simias

Description

@simias

I was playing around trying to get rust to let me get a reference to an explicit memory location (in order to be able to map HW registers in a nice way for the Zinc project) and ended up with that code:

struct S {
    some_stuff: u32,
}

const SOME_S: &'static S = unsafe { &*(0x100 as *const S) };

fn main() {
    println!("{}", SOME_S.some_stuff);
}

Which produces the following error:

rustc: /build/rust-git/src/rust/src/llvm/include/llvm/Support/Casting.h:237: typename llvm::cast_retty<X, Y*>::ret_type llvm::cast(Y*) [with X = llvm::GlobalVariable; Y = llvm::Value; typename llvm::cast_retty<X, Y*>::ret_type = llvm::GlobalVariable*]: Assertion isa(Val) && "cast() argument of incompatible type!"' failed.`

Casting the raw pointer in an intermediate function builds and runs fine however (assuming you have something mapped at 0x100 of course):

struct S {
    some_stuff: u32,
}

const SOME_S: *const S = 0x100 as *const S;

pub fn get_ref<T>(t: *const T) -> &'static T {
    unsafe {
        &*t
    }
}

fn main() {
    println!("{}", get_ref(SOME_S).some_stuff);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions