简体   繁体   中英

What is the best practice of passing reference counted C++ objects to Lua?

I want to have my reference counted C++ object also managed in Lua callbacks: when it is held by a Lua variable, increase its refcount;and when the Lua variable is destroyed, release one refcount. It seems the releasing side can be automatically performed by __gc meta-method, but how to implement the increasing side?

Is it proper&enough to just increase refcount every time before adding the object to Lua stack?

Or maybe I should new a smart pointer object, use it everywhere in Lua C function, then delete it in __gc meta-method? This seems ugly as if something wrong with the Lua execution and the __gc is not called, the new ed smart pointer object will be leaked, and the refcounted object it is referring would have leak one count.

In Perl that I'm more familiar with, this can be achieved by increase refcount at OUTPUT section of XS Map , and decrease refcount at destroyer.

I assume you have implemented two Lua functions in C: inc_ref_count(obj) and dec_ref_count(obj)

local MT = {__gc = dec_ref_count}
local setmetatable = setmetatable
local T = setmetatable({}, {__mode="k"})

function register_object(obj)
   if not T[obj] then
      T[obj] = setmetatable({}, MT)
      inc_ref_count(obj)
   end
end

Invoke register_object(object) on C side every time you send a ref-counted C object to Lua

You may leak memory if Lua VM crashed or was closed.

After more study on Lua manual, I found that light user data does not support metatable (see document ). It should be implemented via heavy user data ( lua_newuserdatauv ) that allocates a chunk of memory by Lua machine. I can placement new a smart pointer object using this memory chunk, and bind a __gc on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM