Safety of restoring trait object from thin pointer knowing concrete type?

I'm exploring how to share pointer to trait object via C FFI and I came up with following

unsafe extern "system" fn callback_enum_windows_until<T: FnMut(HWND) -> i32>(window: HWND, param: LPARAM) -> i32 {
    let func = &mut *(param as *mut T);


Assuming that callback_enum_windows_until instance created with original concrete type.
Would it be correct to cast raw thin pointer to *mut T and then to reference that points to this concrete object?

My idea is to do following:

  • I get closure as generic;
  • For purpose of extending lifetime I store it on box and get thin pointer to it;
  • My callback which is invoked by C code, would get thin pointer and callback which is generic function (and I provided concrete type of closure) I should be able to get pointer and reference to underlying closure(already boxed) as concrete type

Is it sound?

That could be sound, yes. Your snippet isn't enough to tell in your case, though.

Yes, this is correct: you can type-erase the type of the pointee of a raw pointer and then unerase it back. It is indeed useful to manually lay out the dynamic dispatch for callbacks, so as not to have to deal with Rust's dyn objects within FFI. There is a blog post which details this process, but what you are already doing sounds exactly like that, so it's mostly to comfort you rather than guide you :grinning_face_with_smiling_eyes::

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.