lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


* Drake Wilson:

> I'm not the OP, but the problem as I see it is that you may have
> C-level unwind requirements during data transfer from some other
> source into Lua space.
>
> E.g.:
>
>   char const *const str = some_library_get_string();
>   lua_pushstring(L, str);  /* Memory leak if this fails! */
>   some_library_free_string(str);
>
> and in this case you can't even easily use (5.1) lua_cpcall:

I haven't tried this for real yet, but I plan to use a custom userdata
with a __gc meta-method which invokes an embedded clean-up callback.
Your example would then become:

    char const *const str = some_library_get_string();
    clair_push_cleanup(L, some_library_free_string, str);
    lua_pushstring(L, str);  /* Memory leak if this fails! */
    clair_perform_cleanup(L, -2);

If lua_pushstring errors out, the __gc metamethod would perform the
cleanup action.  clair_perform_cleanup performs it immediately,
clearing the pointer.

Formally, it's impossible to implement this in ISO C because you
cannot call a function expecting a pointer to a non-void type through
a function pointer where the function takes a void pointer, but I'm
pretty sure this pattern is fairly common, so it should work.