1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use std::{
ptr, any::Any,
os::raw::{ c_void, c_char }
};
mod rust_box_impl {
use super::*;
pub unsafe extern "C" fn dealloc(object: *mut *mut c_void) {
let object = (object as *mut *mut Box<dyn Any + 'static>).as_mut()
.expect("Unexpected NULL pointer");
if !object.is_null() {
let _opaque = Box::from_raw(*object);
*object = ptr::null_mut();
}
}
pub unsafe extern "C" fn type_hint() -> *const c_char {
b"Rust::Box<dyn Any + 'static>\0".as_ptr() as *const c_char
}
}
#[repr(C)]
pub struct Opaque {
pub dealloc: unsafe extern "C" fn(*mut *mut c_void),
pub type_hint: unsafe extern "C" fn() -> *const c_char,
pub object: *mut c_void
}
impl Opaque {
pub fn type_hint(&self) -> *const c_char {
unsafe{ (self.type_hint)() }
}
pub fn as_rust_box(&self) -> Option<&Box<dyn Any + 'static>> {
match self.type_hint {
_ if self.type_hint == rust_box_impl::type_hint =>
unsafe{ (self.object as *const Box<dyn Any + 'static>).as_ref() }
.expect("Unexpected NULL pointer").into(),
_ => None
}
}
pub fn as_rust_box_mut(&mut self) -> Option<&mut Box<dyn Any + 'static>> {
match self.type_hint {
_ if self.type_hint == rust_box_impl::type_hint =>
unsafe{ (self.object as *mut Box<dyn Any + 'static>).as_mut() }
.expect("Unexpected NULL pointer").into(),
_ => None
}
}
}
impl From<Box<dyn Any + 'static>> for Opaque {
fn from(boxed: Box<dyn Any + 'static>) -> Self {
Self {
dealloc: rust_box_impl::dealloc,
type_hint: rust_box_impl::type_hint,
object: Box::into_raw(Box::new(boxed)) as *mut c_void
}
}
}
impl Drop for Opaque {
fn drop(&mut self) {
unsafe{ (self.dealloc)(&mut self.object) }
}
}