Created
July 16, 2019 19:50
-
-
Save rust-play/2011c7455c725938b3edb33560c177d1 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[derive(Debug)] | |
#[repr(C)] | |
struct MyStruct<T, U> { | |
height: Option<T>, | |
width: Option<T>, | |
age: u32, | |
othertype: U, | |
} | |
fn main() -> Result<(), Box<dyn std::error::Error>> { | |
let mut value: MyStruct<i32, u8> = MyStruct { | |
height: Some(22003), | |
width: None, | |
age: 100, | |
othertype: 25u8, | |
}; | |
println!("value == {:#?}", value); | |
let value_bytes = | |
unsafe { &mut *(&mut value as *mut MyStruct<i32, u8> as *mut [u8; std::mem::size_of::<MyStruct<i32, u8>>()]) }; | |
println!("value_bytes = {:?}", value_bytes); | |
let value_reconstructed = | |
unsafe { &mut *(value_bytes as *mut [u8; std::mem::size_of::<MyStruct<i32, u8>>()] as *mut MyStruct<i32, u8>) }; | |
println!("value_reconstructed == {:#?}", value_reconstructed); | |
println!("Modify value_reconstructed"); | |
value_reconstructed.height = None; | |
value_reconstructed.age = 101; | |
value_reconstructed.width = Some(35); | |
println!("value_reconstructed == {:#?}", value_reconstructed); | |
println!("value == {:#?}", value); | |
println!("value_bytes = {:?}", value_bytes); | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment