gpt4 book ai didi

rust - Box 在 dylib 模块中向下转换返回 None

转载 作者:行者123 更新时间:2023-11-29 07:44:50 31 4
gpt4 key购买 nike

我使用 dylib 作为插件解决方案。当我调用函数时 register (下面代码中,fun是我的项目名):

let register = plugin.get::<unsafe extern fn(&mut fun::mem::Mem)>("register").unwrap();
unsafe {
register(&mut mem);
}

在 dylib 的 register 中功能,mem.get_mut::<fun::router::Router>("router")返回 None

但如果我使用 mem.get_mut::<fun::router::Router>("router")main.rs .它返回 Router如我所愿。

我测试了更多并得到了以下结果:

在动态库中:

  • mem.get_mut::<String>("test")工作得很好。
  • mem.get_mut::<fun::Bob>("bob")返回 None .

main.rs :

  • mem.get_mut::<String>("test")工作得很好。
  • mem.get_mut::<fun::Bob>("bob")工作顺利。

我的问题:

如果在 Main 模块中定义了 downcast 的泛型类型,为什么 downcast_mut 在 dylib 中返回 None?

内存结构:

#[derive(Debug)]
pub struct Mem {
pub value: HashMap<String, Box<Any>>,
}

get_mut:

pub fn get_mut<T: Any>(&mut self, key: &str) -> Option<&mut T> {
match self.value.get_mut(key) {
Some(val) => {
match val.downcast_mut::<T>() {
Some(value) => Some(value),
None => None,
}
}
None => None,
}
}

抱歉我的描述不当。

更新:

TypeId测试结果:

# in dylib's function:
Router TypeId: TypeId { t: 10245301028242226491 }
String TypeId: TypeId { t: 2231836747111135853 }

# in `main.rs`'s function:
Router TypeId: TypeId { t: 11005875220745415326 }
String TypeId: TypeId { t: 2231836747111135853 }

TypeId 不同。这个问题有什么解决办法吗?

最佳答案

如前所述,直到现在 (1.10) TypeId 在 crate 或编译中都不稳定。

@eddyb 就在本周登陆了 pull request这使得 TypeId 成为唯一的跨 crate ,这将启用您的特定用例。

重要的是要注意这种稳定性并不完全;例如,如果您阅读注释,您会注意到 TypeId 可能会随着编译器版本或 crate 版本的变化而变化。尽管如此,对于单个编译器和共享依赖项,它现在在重新编译时是稳定的。

现在,您可以使用夜间编译器,或者等到包含此补丁的下一个稳定版本(我想是 1.12 或 1.13)。

关于rust - Box<Any> 在 dylib 模块中向下转换返回 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38683432/

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