簡體   English   中英

將Lua類對象存儲到C指針,並將其推回Lua Stack

[英]Store Lua class object to C pointer and push it back to Lua Stack

使用自制的Lua C ++綁定,我可以創建可從Lua腳本獲得的C ++類。

現在,我想在Lua腳本中創建類對象,將其引用存儲在C ++中,並在需要時從C ++代碼中調用此Lua類對象的函數。

在Lua腳本中,我創建了一個帶有全局函數的類對象,將該類對象傳遞給C ++代碼。

MyClass = {}

function MyClass:hello()
    debug.codeSite.sendMsg( "MyClass:hello()" )
end

function MyClass:new()
  local tNewClass = {}

  setmetatable( tNewClass, self )
  self.__index = self

  return tNewClass
end

local tClass = MyClass:new()

function getClass()
    debug.codeSite.sendMsg( "Return class object" )
    return tClass;
end

現在在C ++中,我想獲取其實例並調用函數hello()。 這是我嘗試的:

  1. 調用getClass(),以便將Lua對象(一個表)壓入堆棧。
  2. 使用函數lua_topointer()將其地址存儲到C ++ const void *中。

在這一點上,我不知道如何將這個指針推回Lua堆棧,因此Lua表被推回了堆棧,壓入了函數名,然后調用了它。

所有這些的想法是在Lua腳本中創建幾個對象,然后在C ++中使用它們。

在lua中:

tObject1 = MyClass:new()
tObject2 = MyClass:new()

在C ++中,在需要時使用tObject1:hello()或tObject2:hello()。

編輯:

根據lua_topointer()的描述 ,將Lua表轉換為C指針僅用於調試目的。

謝謝。

使用luaL_ref()將lua對象存儲在預定義的Lua注冊表中,並在c ++中保存返回的整數索引。 當您需要將Lua對象放在Lua堆棧上時,請使用較早檢索到的索引通過lua_rawgeti()從注冊表中讀取它。 當您不再需要c ++方面的對象時,請不要忘記使用luaL_unref()取消引用對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM