简体   繁体   English

将引用计数的 C++ 对象传递给 Lua 的最佳实践是什么?

[英]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;我想让我的引用计数 C++ object 也在 Lua 回调中进行管理:当它由 Z0AE9448 变量持有时,EFA9478A1DB9D1E2C64 增加and when the Lua variable is destroyed, release one refcount.当 Lua 变量被破坏时,释放一个引用计数。 It seems the releasing side can be automatically performed by __gc meta-method, but how to implement the increasing side?看起来释放端可以通过__gc元方法自动执行,但是增加端如何实现呢?

Is it proper&enough to just increase refcount every time before adding the object to Lua stack?在将 object 添加到 Lua 堆栈之前,每次只增加引用计数是否合适&足够?

Or maybe I should new a smart pointer object, use it everywhere in Lua C function, then delete it in __gc meta-method? 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.这看起来很难看,好像 Lua 执行有问题并且没有调用__gc的 ed 智能指针 object 将被泄露,引用的 object 将泄露一个计数。

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.在我更熟悉的Perl中,这可以通过增加XS MapOUTPUT部分的引用计数并减少破坏者的引用计数来实现。

I assume you have implemented two Lua functions in C: inc_ref_count(obj) and dec_ref_count(obj)我假设您已经在 C 中实现了两个 Lua 函数: inc_ref_count(obj)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每次发送引用计数 C object 到 C object 到 C 时,在 C 端调用register_object(object)

You may leak memory if Lua VM crashed or was closed.如果 Lua VM 崩溃或关闭,您可能会泄漏 memory。

After more study on Lua manual, I found that light user data does not support metatable (see document ).在对 Lua 手册进行了更多研究后,我发现轻量级用户数据不支持元表(参见文档)。 It should be implemented via heavy user data ( lua_newuserdatauv ) that allocates a chunk of memory by Lua machine.它应该通过大量用户数据( lua_newuserdatauv )来实现,该数据由 Lua 机器分配一块 memory。 I can placement new a smart pointer object using this memory chunk, and bind a __gc on it.我可以使用此 memory 块放置新的智能指针 object,并在其上绑定__gc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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