Skip to content

Commit 3af3b58

Browse files
committed
C++: Move the interpreter ComponentCompiler on the heap
It is too fragile otherwise
1 parent 6b37764 commit 3af3b58

File tree

1 file changed

+8
-18
lines changed

1 file changed

+8
-18
lines changed

internal/interpreter/ffi.rs

Lines changed: 8 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -722,44 +722,34 @@ pub struct Diagnostic {
722722
level: DiagnosticLevel,
723723
}
724724

725-
#[repr(C)]
726-
#[cfg(target_pointer_width = "64")]
727-
pub struct ComponentCompilerOpaque([usize; 16]);
728-
729-
#[repr(C)]
730-
#[cfg(target_pointer_width = "32")]
731-
#[repr(align(8))]
732-
pub struct ComponentCompilerOpaque([usize; 19]);
733-
734-
/// Asserts that ComponentCompilerOpaque is as large as ComponentCompiler and has the same alignment, to make transmute safe.
735-
const _: [(); std::mem::size_of::<ComponentCompilerOpaque>()] =
736-
[(); std::mem::size_of::<ComponentCompiler>()];
737-
const _: [(); std::mem::align_of::<ComponentCompilerOpaque>()] =
738-
[(); std::mem::align_of::<ComponentCompiler>()];
725+
#[repr(transparent)]
726+
pub struct ComponentCompilerOpaque(NonNull<ComponentCompiler>);
739727

740728
impl ComponentCompilerOpaque {
741729
fn as_component_compiler(&self) -> &ComponentCompiler {
742730
// Safety: there should be no way to construct a ComponentCompilerOpaque without it holding an actual ComponentCompiler
743-
unsafe { std::mem::transmute::<&ComponentCompilerOpaque, &ComponentCompiler>(self) }
731+
unsafe { self.0.as_ref() }
744732
}
745733
fn as_component_compiler_mut(&mut self) -> &mut ComponentCompiler {
746734
// Safety: there should be no way to construct a ComponentCompilerOpaque without it holding an actual ComponentCompiler
747-
unsafe { std::mem::transmute::<&mut ComponentCompilerOpaque, &mut ComponentCompiler>(self) }
735+
unsafe { self.0.as_mut() }
748736
}
749737
}
750738

751739
#[no_mangle]
752740
pub unsafe extern "C" fn slint_interpreter_component_compiler_new(
753741
compiler: *mut ComponentCompilerOpaque,
754742
) {
755-
std::ptr::write(compiler as *mut ComponentCompiler, ComponentCompiler::default())
743+
*compiler = ComponentCompilerOpaque(NonNull::new_unchecked(Box::into_raw(Box::new(
744+
ComponentCompiler::default(),
745+
))));
756746
}
757747

758748
#[no_mangle]
759749
pub unsafe extern "C" fn slint_interpreter_component_compiler_destructor(
760750
compiler: *mut ComponentCompilerOpaque,
761751
) {
762-
drop(std::ptr::read(compiler as *mut ComponentCompiler))
752+
drop(Box::from_raw((*compiler).0.as_ptr()))
763753
}
764754

765755
#[no_mangle]

0 commit comments

Comments
 (0)