I use dylib as plugin solution. When I call function register
(in the code below, fun
is my project name):
let register = plugin.get::<unsafe extern fn(&mut fun::mem::Mem)>("register").unwrap();
unsafe {
register(&mut mem);
}
In dylib's register
function, mem.get_mut::<fun::router::Router>("router")
return None
But if I use mem.get_mut::<fun::router::Router>("router")
in main.rs
. It return Router
as I want.
I test more and get some result below:
In dylib:
mem.get_mut::<String>("test")
work well.mem.get_mut::<fun::Bob>("bob")
returnNone
.
In main.rs
:
mem.get_mut::<String>("test")
work well.mem.get_mut::<fun::Bob>("bob")
work well.
My question:
Why downcast_mut return None in dylib if downcast's generic type defined in Main module ?
mem struct:
#[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,
}
}
Sorry for my poor description.
Update:
TypeId test result:
# 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 is different. Any solution for this problem?
TypeId
s (whichAny
is internally based on) are not stable across compilations. It's likely returningNone
because each component has a different idea of what the unique ID forfun::Bob
is, thus they "see" different types. You can verify this by runningprintln!("{:?}", ::std::any::TypeId::of::<Bob>());
in both components and checking the output.String
? Is this an accident, a specificity ofstd
, or the key to making it work for user-written types?