mikluha
mikluha

Reputation: 65

Casting a C pointer to a struct, in Rust

I have bindings in Rust for a library in C and they aren't complete.

In C code I have a macros defined, simplified, like this:

  #define MY_MACROS1(PTR) (((my_struct1 *) (PTR))->field1.field2 >> 2)

I need to achieve the same thing in Rust.

I have a Rust binding definition for my_struct1. And I have a pointer

  let my_ptr1: usize = unsafe { get_a_pointer_from_c(); }

How can I cast a pointer my_ptr1 to my_struct1 or rather to my_struct1 * ?

Rust binding to get_a_pointer_from_c() returns a pointer of type usize, note.

Upvotes: 2

Views: 2850

Answers (1)

Masklinn
Masklinn

Reputation: 42272

  • Option 1 would be what Ôrel suggested: have the C side expose the proper accessor as a function, and call that from Rust.

  • option 2 is to define the C struct on the Rust side and cast your pointer to a pointer / ref to that on the Rust side e.g.

    let mut p;
    let r = unsafe {
        p = ptr::NonNull::new(
            get_pointer_from_c() as *mut YourType
        ).unwrap();
        p.as_mut()
    };
    

Upvotes: 3

Related Questions