Skip to content

Instantly share code, notes, and snippets.

@Denys-Bushulyak
Last active February 24, 2024 12:02
Show Gist options
  • Save Denys-Bushulyak/b75d2e124532bf5b4c1b7d70ec8214ae to your computer and use it in GitHub Desktop.
Save Denys-Bushulyak/b75d2e124532bf5b4c1b7d70ec8214ae to your computer and use it in GitHub Desktop.
Point to Structure in Rust in 2 versions
#[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);
}
@Denys-Bushulyak
Copy link
Author

Example how to cast pointer to struct.

@fulup-bzh
Copy link

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.

@Denys-Bushulyak
Copy link
Author

Denys-Bushulyak commented Dec 13, 2022

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment