简体   繁体   English

在 Rust 中将 C 指针转换为结构

[英]Casting a C pointer to a struct, in Rust

I have bindings in Rust for a library in C and they aren't complete.我在 C 中有一个库的 Rust 绑定,但它们并不完整。

In C code I have a macros defined, simplified, like this:在 C 代码中,我定义了一个简化的宏,如下所示:

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

I need to achieve the same thing in Rust.我需要在 Rust 中实现相同的目标。

I have a Rust binding definition for my_struct1 .我有my_struct1的 Rust 绑定定义。 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 * ?如何将指针my_ptr1my_struct1或更确切地说是my_struct1 *

Rust binding to get_a_pointer_from_c() returns a pointer of type usize , note. Rust 绑定到get_a_pointer_from_c()返回一个usize类型的指针,注意。

  • Option 1 would be what Ôrel suggested: have the C side expose the proper accessor as a function, and call that from Rust.选项 1 是 Ôrel 建议的:让 C 侧将正确的访问器公开为 function,并从 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 eg选项 2 是在 Rust 侧定义 C 结构,并将指针转换为 Rust 侧的指针/引用,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM