简体   繁体   中英

Trying to pin box a dynamic writer to pass it across FFI with no luck in RUST

I seem to have a basic problem that I can't solve.

I have this struct that expects apinned dynamic writer to pass to "C" and then later gets it back as a part of a callback function:

Here is the struct:

pub struct ExecutionContext<'a> {
    pub log: Pin<&'a mut Box<dyn std::io::Write>>,
}

I can't seem to find a way to pass a simple stderr to this struct though.

If I try

let mut stderr2 = Pin::new (&mut Box::<dyn Write>::new(stderr()));

I get this error:

function or associated item cannot be called on `Box<dyn std::io::Write>` due to unsatisfied trait bounds

When I try this:

 let mut stderr2 = Pin::new (&mut Box::new(stderr()));
 let mut ctx = ExecutionContext{
     log: stderr2,
 };

I get:

expected trait object `dyn std::io::Write`, found struct `Stderr`

The first error continues with:

the following trait bounds were not satisfied: dyn std::io::Write: Sized

The problem is that somehow calling Box::new with this type bounds requires the inner value of the Box to have a known size. Trait objects cannot provide that. You can avoid that by creating explicitly a variable with your type annotations.

let mut b: Box<dyn Write> = Box::new(stderr());
let stderr2 = Pin::new(&mut b);
let mut ctx = ExecutionContext { log: stderr2 };

playground

But may I ask for the reason of putting a Box behind a mutable reference? Isn't a Box enough?

If you are willing to change the type of ExecutionContext::log I would recommend the following:

  • store the Box directly behind the Pin in ExecutionContext::log (without the reference)
  • use Box::pin , a constructor which creates a Pin<Box<T>> for you
pub struct ExecutionContext {
    pub log: Pin<Box<dyn std::io::Write>>,
}

let stderr2 = Box::pin(stderr());
let mut ctx = ExecutionContext { log: stderr2 };

playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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