[英]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.