gpt4 book ai didi

rust - 创建 *mut *mut 到一个结构

转载 作者:行者123 更新时间:2023-11-29 07:50:12 26 4
gpt4 key购买 nike

我正在尝试使用指向我的结构的指针调用 pthread_join,以便 C 线程可以将结构填充到我指向它的内存中。 (是的,我知道这是非常不安全的..)

pthread_join的函数签名:

pub unsafe extern fn pthread_join(native: pthread_t,
value: *mut *mut c_void)
-> c_int

我这样做是为了练习将 C 代码从书中移植到 Rust。 C代码:

pthread_t   tid1;
struct foo *fp;
err = pthread_create(&tid1, NULL, thr_fn1, NULL);
err = pthread_join(tid1, (void *)&fp);

我想出了这段代码:

extern crate libc;
use libc::{pthread_t, pthread_join};

struct Foo {}

fn main() {
let tid1:pthread_t = std::mem::uninitialized();
let mut fp:Box<Foo> = std::mem::uninitialized();
let value = &mut fp;
pthread_join(tid1, &mut value);
}

但我看到的错误是:

error[E0308]: mismatched types
--> src/bin/11-threads/f04-bogus-pthread-exit.rs:51:24
|
51 | pthread_join(tid1, &mut value);
| ^^^^^^^^^^ expected *-ptr, found mutable reference
|
= note: expected type `*mut *mut libc::c_void`
found type `&mut &mut std::boxed::Box<Foo>`

是否有可能仅使用转换来实现这一点,还是我需要转化?

最佳答案

这里有几个问题:

  • Box 是指向堆分配资源的指针,您可以使用 Box::into_raw(some_box) 提取指针本身,
  • 引用不会默默地强制转换为指针(即使它们具有相同的表示),您需要显式转换,
  • 您需要从您的具体类型转换为c_void,类型推断或许可以做到这一点
  • 你有一个对指针的引用,你需要一个指向指针的指针;你的间接层级太多了。

让它发挥作用:

// pthread interface, reduced
struct Void;

fn sample(_: *mut *mut Void) {}

// actual code
struct Foo {}

fn main() {
let mut p = Box::into_raw(Box::new(Foo{})) as *mut Void;
sample(&mut p as *mut _);
}

请注意,这是内存泄漏(由于 into_raw),通常应使用 from_raw 将内存推回 Box用于调用 Foo 的析构函数并释放内存。

关于rust - 创建 *mut *mut 到一个结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42235980/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com