Actual limitations of asynchronous callbacks from C?


“The book” has a section on the FFI page on asynchronous callbacks from threads generated by C code. It’s a bit vague, except to suggest you should probably pass the data to a Rust thread through a channel.

What do you actually need to avoid doing in such a callback? There are some Windows APIs that create a thread or queue items to a threadpool, and OSX now has some similar concepts. I could bury it all in a C library, but I’d prefer to stay in Rust if possible.


Link to relevant section: Asynchronous callbacks

(I’m curious and would like to know more too!)


The main thing to worry about is that it’s undefined behavior to panic through a layer of non-Rust code. The std::panic::{recover, propagate} functions can be used (in nightlies) to deal with this kind of thing. For example, in the read_func callback that I pass to Secure Transport, I capture panics that the underlying Rust stream generates, store the payload off to the side, and then propagate it when execution reaches Rust code again.