gpt4 book ai didi

rust - 如何解决 RefCell 问题?

转载 作者:行者123 更新时间:2023-11-29 08:22:10 26 4
gpt4 key购买 nike

我有一个包含两个 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 执行期间被调用这需要 my_struct.borrow_mut() ,但是my_struct已借c_call需要p1p2 ,所以我得到 RefCell<T> already borrowed .

问题是 c_call无法更改,它需要对 p1 的不可变访问权限和 p2还有一些borrow_mutmy_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);
}
}

( Playpen )

我该如何解决这个问题?

最佳答案

您的问题是,在 c_call 调用的参数中调用 borrow() 将借用对象,直到调用完成。如果你把它改成

let (p1, p2) = {
let x = my_struct.borrow();
(x.p1, x.p2)
};
c_call(p1, p2, my_struct.clone());

然后借用在 c_call 调用之前结束,因此 c_call 也可以 borrow_mut 您的对象。

关于rust - 如何解决 RefCell 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35626006/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com