Last active
February 24, 2024 12:02
-
-
Save Denys-Bushulyak/b75d2e124532bf5b4c1b7d70ec8214ae to your computer and use it in GitHub Desktop.
Point to Structure in Rust in 2 versions
This file contains hidden or 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
#[allow(dead_code)] | |
#[derive(Debug, Copy, Clone)] | |
struct A<'text> { | |
foo: &'text str, | |
baz: i32, | |
} | |
fn ptr_to_struct(p: *const A) { | |
let b: A = unsafe { *p }; // main part of this example! | |
println!("{:#?}", b); | |
} | |
fn ptr_to_struct_2(p: usize) { | |
let b = unsafe { *(p as *const A) }; // main part of this example! | |
println!("{:#?}", b); | |
} | |
fn main() { | |
let a = A { | |
foo: "Hello", | |
baz: 2000, | |
}; | |
ptr_to_struct(&a); | |
ptr_to_struct_2(&a as *const _ as usize); | |
} |
Thank you for this example, I've been searching for hours before finding the right model to call a C-routine that take as argument an address of pointer to interface with a C routine looking like: Myfunc (MyCType **value){}.
Your code would deserve to land within official RUST documentation.
Thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example how to cast pointer to struct.