[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Properly binding C libraries using callbacks
- From: Doug Currie <doug.currie@...>
- Date: Thu, 20 Oct 2011 18:00:24 -0400
On Oct 20, 2011, at 5:07 PM, Rob Hoelz wrote:
> Can someone give me some pointers on the proper way to bind a library that uses callbacks, especially one that doesn't
> allow you to thread your own userdata through the callbacks? Coroutines make it tricky, and my understanding is that
> storing things in global variables in the binding are a faux pas.
There are several approaches.
1. Put the onus on the library user to make sure the thread that creates the callback remains in existence at least as long as the callback may be executed, i.e., punt
2. When a callback is created, put the thread in a table maintained by the library for the purpose of preventing the thread from being garbage collected; this table can be in the library's environment (or be an upvalue of the library's functions) or may be in the registry
3. When the library is loaded, capture the thread into which it is loaded (which is more likely to the the main thread) and use that thread for callbacks; optionally add #2 to keep this thread from being collected
4. When the library is loaded, create a new thread that is used exclusively to process callbacks; use #2 to prevent this thread from being collected
5. In Lua 5.2 use LUA_RIDX_MAINTHREAD to get a handle on the main thread and use it for callbacks
Of these options, #4 is the safest in Lua 5.1, but uses extra memory.
e