2

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.

3
  • 1
    Why not do a function on C to return the value that looks like to be an int ? Commented Jun 24, 2020 at 6:50
  • What keeps you from doing it exactly the same way as shown? Commented Jun 24, 2020 at 8:02
  • I believe the ` \ ` is a typo or a copy-paste error, or an accident concerning newline white space. Commented Jun 24, 2020 at 8:02

1 Answer 1

3
  • 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()
    };
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.