【发布时间】:2018-03-01 05:15:33
【问题描述】:
我正在尝试使用静态变量通过 C 回调提供闭包。我能够使用Fn 类型来处理事情,但我想通过FnMut 让它工作,以便为图书馆的用户提供更多的多功能性。
这是我所拥有的:
lazy_static! {
static ref CALLBACK: Mutex<RefCell<Box<FnMut(Result<&str>) + Send>>> = Mutex::new(RefCell::new(Box::new(|_|())));
}
fn wrap_cb<F: Fn(Result<&str>)>(f: Option<F>) -> Option<unsafe extern "C" fn(*mut c_char, size_t)> {
match f {
Some(_) => {
unsafe extern "C" fn wrapped(msg: *mut c_char, len: size_t) {
let s = std::str::from_utf8(std::slice::from_raw_parts(msg as *const u8, len))
.map_err(Error::from);
let x = CALLBACK.lock().unwrap();
x.borrow_mut()(s);
}
Some(wrapped)
}
None => None,
}
}
这给出了错误:
error[E0596]: cannot borrow immutable `Box` content as mutable
--> src/wpactrl.rs:56:17
|
56 | x.borrow_mut()(s);
| ^^^^^^^^^^^^^^ cannot borrow as mutable
【问题讨论】:
标签: static rust closures mutex