Rust FFI, callbacks, and lifetimes

≡放荡痞女 提交于 2021-01-29 08:34:02

问题


I'm trying to build a nice rust wrapper around libuv, an event loop library written in C. I'm pretty much "done", but I'm having some trouble with callbacks and lifetimes.

Being an event loop library, libuv relies heavily on callbacks. I have some code that can accept functions, closures, or a tuple of (obj, method-on-obj) and it handles creating an appropriate "trampoline" to get that across the FFI boundary. That all works.

However, the problem I'm running into is that I cannot figure out what to do about lifetimes. At this point, I'm requiring that these functions/closures/objs have static lifetimes, but that creates a ton of headaches when it comes to actually using my library: any data accessed by these functions/closures/objs must also be static, then. In simple cases, a move on a closure can "fix" the problem, but any real-world use case is going to very quickly become cumbersome - for example, creating a static object in rust is difficult, so the (obj, method-on-obj) callback type isn't very useful - but I'd really like it to be!

I can't really think of any other solutions, though. The callbacks and their data must live until they are stopped, cancelled, or closed via an appropriate libuv function - or until the loop ends. I don't know if it's possible to pass a lifetime through an FFI boundary, but, even if it is, I'm pretty sure rust's analysis would conclude that the lifetimes are essentially static anyway - I couldn't imagine any way to statically conclude any shorter lifetime via code analysis since it's determined at runtime.

So, I'm wondering if anyone has any ideas to make my library easier to use either by somehow reducing lifetime expectations, or making it easier and less cumbersome to deal with making everything static. Any help is appreciated!

来源:https://stackoverflow.com/questions/61687193/rust-ffi-callbacks-and-lifetimes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!