← Back to context

Comment by stevefan1999

25 days ago

As a side note, there is a libffi wrapper on Rust that is exactly leveraging this code and data separation of closures in Rust: https://docs.rs/libffi

I've been using this on my vibewasm project to provide host function conversion to keep a C callable function in the front surface but doing my own custom wasm calling convention while capturing a persistent context pointer to the wasm store.

There is a side effect though: it is essentially unsound as you have to leak the object to the libffi closure which is a form of JIT -- dynamic code generation, it is, meaning Rust will have no way of knowing the lifetime of the pointer, or you have to always keep the libffi closure alive, meaning it is a permanent leak. I tried mitigate this by storing the closure in the wasm store, and we use that as the ultimate closure lifetime by designation -- any libffi function callback post store destruction is undefined behavior though.