Call a raw address from Rust

后端 未结 1 433
猫巷女王i
猫巷女王i 2020-12-04 01:56

I am writing an OS in Rust and need to directly call into a virtual address that I\'m calculating (of type u32). I expected this to be relatively simple:

<
相关标签:
1条回答
  • 2020-12-04 02:25

    Casts of the type _ as f-ptr are not allowed (see the Rustonomicon chapter on casts). So, as far as I can tell, the only way to cast to function pointer types is to use the all mighty weapon mem::transmute().

    But before we can use transmute(), we have to bring our input into the right memory layout. We do this by casting to *const () (a void pointer). Afterwards we can use transmute() to get what we want:

    let ptr = virtual_address as *const ();
    let code: extern "C" fn() = unsafe { std::mem::transmute(ptr) };
    (code)();
    

    However, a few notes on this:

    • If you, future reader, want to use this to do simple FFI things: please take a moment to think about it again. Calculating function pointers yourself is rarely necessary.
    • Usually extern "C" functions have the type unsafe extern "C" fn(). This means that those functions are unsafe to call. You should probably add the unsafe to your function.
    0 讨论(0)
提交回复
热议问题