我有一个带有两个 C 指针和一个 Rust 的结构HashMap
。
struct MyStruct {
p1: *mut ...,
p2: *mut ...,
hm: Box<HashMap<...>>
}
我的结构被处理为一个Rc<RefCell<MyStruct>>
,我有一个像这样调用的 C 函数:
c_call(my_struct.borrow().p1, my_struct.borrow().p2);
C 有一个 Rust 回调,它在执行过程中被调用c_call
,需要 a my_struct.borrow_mut()
,但my_struct
已经借用了c_call
哪个需要p1
和p2
,所以我得到RefCell<T> already borrowed
.
问题是c_call
无法更改,它需要不可变访问p1
和p2
一些borrow_mut
.my_struct
这是一个 MCVE:
use std::cell::RefCell;
use std::collections::HashMap;
use std::mem::uninitialized;
use std::os::raw::c_void;
use std::rc::Rc;
struct MyStruct {
p1: *mut c_void,
p2: *mut c_void,
hm: Box<HashMap<String, String>>
}
// c_call can't mutate hm because my_struct is already borrowed
// c_call can't be changed
fn c_call(_p1: *mut c_void, _p2: *mut c_void, my_struct: Rc<RefCell<MyStruct>>) {
my_struct.borrow_mut().hm.insert("hey".to_string(), "you".to_string());
}
// call only receives Rc<RefCell<MyStruct>> and need to call c_call
fn call(my_struct: Rc<RefCell<MyStruct>>) {
c_call(my_struct.borrow().p1, my_struct.borrow().p2, my_struct.clone());
}
fn main() {
unsafe {
let my_struct = MyStruct {
p1: uninitialized::<*mut c_void>(), // irrelevant
p2: uninitialized::<*mut c_void>(),
hm: Box::new(HashMap::new())
};
let my_struct = Rc::new(RefCell::new(my_struct));
call(my_struct);
}
}
(游戏围栏)
我该如何解决这个问题?