繁体   English   中英

试图将动态写入器固定在 FFI 中,但在 RUST 中没有运气

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

我似乎有一个我无法解决的基本问题。

我有这个结构,它期望固定的动态编写器传递给“C”,然后作为回调 function 的一部分将其取回:

这是结构:

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

不过,我似乎找不到将简单的 stderr 传递给该结构的方法。

如果我尝试

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

我收到此错误:

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

当我尝试这个时:

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

我得到:

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

第一个错误继续:

不满足以下特征界限: dyn std::io::Write: Sized

问题在于,以某种方式调用Box::new与这种类型边界需要Box的内部值具有已知大小。 特征对象无法提供这一点。 您可以通过使用类型注释显式创建变量来避免这种情况。

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

操场

但是我可以问一下将 Box 放在可变引用后面的原因吗? 一个Box还不够吗?

如果您愿意更改ExecutionContext::log的类型,我会推荐以下内容:

  • Box直接存储在ExecutionContext::log中的Pin后面(没有引用)
  • 使用Box::pin ,一个为您创建Pin<Box<T>>的构造函数
pub struct ExecutionContext {
    pub log: Pin<Box<dyn std::io::Write>>,
}

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

操场

暂无
暂无

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

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