【问题标题】:How to get a mutable u32 pointer and cast it into an int pointer of C如何获取可变 u32 指针并将其转换为 C 的 int 指针
【发布时间】:2018-10-15 07:35:02
【问题描述】:

假设我有一个 C 函数:

void func(char *buf, unsigned int *len);

为了在 Rust 中调用它,我声明:

pub fn func(buf: *mut ::std::os::raw::c_char, len: *mut ::std::os::raw::c_uint) {
    unimplemented!()
}

然后我又写了一个包装器:

pub fn another_func() -> String {
    let mut capacity: u32 = 256;
    let mut vec = Vec::with_capacity(capacity as usize);
    unsafe {
        func(vec.as_ptr() as *mut c_char, &capacity as *mut c_uint)
    };
    String::from_utf8(vec).unwrap();
    unimplemented!()
}

但是编译器告诉我:

error[E0606]: casting `&u32` as `*mut u32` is invalid
   --> src/main.rs:...:28
    |
307 |                                  &capacity as *mut c_uint)

为什么我不能将capacity 转换为*mut c_unit

【问题讨论】:

  • 请注意,在这种情况下不需要unsafe,因为将某些内容转换为指针是完全安全的,但取消引用指针是不安全的。
  • 第二个注意事项:您应该接受 size_t 而不是 unsigned int 用于 C 中的(数组)大小。请参阅 stackoverflow.com/questions/2550774/what-is-size-t-in-c
  • 第三个注意事项:您必须使用#[no_mangle] 禁用名称修改才能从C 调用它。
  • 第四点:我怀疑,你想修改func函数中的vec。确保您使用set_len(这是不安全的)来设置Vec 的长度。
  • @hellow 谢谢。对于第二个:实际上我在这里需要 uint32_t,但我不想在 api 标头中包含太多像 stdint.h 这样的标头。 size_t可能很长,比uint32_t长,不适合。

标签: rust ffi


【解决方案1】:

我必须使引用可变。

func(vec.as_ptr() as *mut c_char, &mut capacity as *mut c_uint)

【讨论】:

    猜你喜欢
    • 2021-01-16
    • 2017-02-12
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    • 2018-06-08
    • 2012-12-15
    • 1970-01-01
    • 2012-03-02
    相关资源
    最近更新 更多