我有一个值,我想在我自己的类型中存储该值以及对该值内部内容的引用:
struct Thing {
count: u32,
}
struct Combined<'a>(Thing, &'a u32);
fn make_combined<'a>() -> Combined<'a> {
let thing = Thing { count: 42 };
Combined(thing, &thing.count)
}
Run Code Online (Sandbox Code Playgroud)
有时候,我有一个值,我想在同一个结构中存储该值和对该值的引用:
struct Combined<'a>(Thing, &'a Thing);
fn make_combined<'a>() -> Combined<'a> {
let thing = Thing::new();
Combined(thing, &thing)
}
Run Code Online (Sandbox Code Playgroud)
有时,我甚至没有参考该值,我得到同样的错误:
struct Combined<'a>(Parent, Child<'a>);
fn make_combined<'a>() -> Combined<'a> {
let parent = Parent::new();
let child = parent.child();
Combined(parent, child)
}
Run Code Online (Sandbox Code Playgroud)
在每种情况下,我都会收到一个错误,即其中一个值"活不够长".这个错误是什么意思?
tokio教程的select!
状态:
需要注意的是,要等待引用,被引用的值必须被固定或实现 Unpin。
事实上,以下代码无法编译:
let fut = example(); // example is an async fn
(&mut fut).await;
Run Code Online (Sandbox Code Playgroud)
并出现以下错误消息:
error[E0277]: `from_generator::GenFuture<[static generator@src/main.rs:15:27: 17:2]>` cannot be unpinned
... snip ...
within `impl futures::Future<Output = i32>`, the trait `Unpin` is not implemented for `from_generator::GenFuture<[static generator@src/main.rs:15:27: 17:2]>
... snip ...
note: consider using `Box::pin`
Run Code Online (Sandbox Code Playgroud)
固定未来可以解决这个问题:
error[E0277]: `from_generator::GenFuture<[static generator@src/main.rs:15:27: 17:2]>` cannot be unpinned
... snip ...
within `impl futures::Future<Output = i32>`, the trait `Unpin` is not implemented for `from_generator::GenFuture<[static generator@src/main.rs:15:27: 17:2]>
... snip …
Run Code Online (Sandbox Code Playgroud) 我有使用数据调用 Rust 代码的 C++ 代码。它知道将数据发送到哪个对象。下面是 C++ 回调的 Rust 函数示例:
extern "C" fn on_open_vpn_receive(
instance: Box<OpenVpn>,
data: *mut c_uchar,
size: *mut size_t,
) -> u8
Run Code Online (Sandbox Code Playgroud)
它将指针作为 a 接收Box
,因此我创建了一个函数openvpn_set_rust_parent
来设置 C++ 必须回调的对象。这个对象是一个指向自身的指针。我正在使用,Pin
因此Box
不会重新分配到其他地方,从而使 C++ 调用无效地址。
impl OpenVpn {
pub fn new() -> Pin<Box<OpenVpn>> {
let instance = unsafe { interface::openvpn_new(profile.as_ptr()) };
let o = OpenVpn { instance: instance };
let p = Box::pin(o);
unsafe {
interface::openvpn_set_rust_parent(o.instance, p.as_ptr());
};
p
}
}
Run Code Online (Sandbox Code Playgroud)
签名:
pub fn openvpn_set_rust_parent(instance: *mut …
Run Code Online (Sandbox Code Playgroud)