我正在開發一個庫。我想在庫中使用回調函數來註冊將從Lua環境中調用的事件。我的庫具有所有低層功能(在文件-reg_callback.cpp & reg_callback.h中)。所有更高層功能都將在Lua環境中(Lua腳本)。如何在C++庫文件中使用回調函數?
http://opensourceforu.com/2012/02/function-pointers-and-callbacks-in-c-an-odyssey/
參考該鏈接,下一個簡單的回調函數;我的main()是在Lua腳本中,我在庫中有一個Lua包裝器。我的代碼看起來像這樣。
enter code here typedef void(*callback)(char*); <br/> bool register_callback(callback ptr_reg_callback); <br/>// reg_callback.cpp bool <br/>register_callback(callback ptr_reg_callback)<br/> {
<br/> (*ptr_reg_callback)();
<br/> return true;<br/>} <br/>// Lua_wrapper_for_callback.cpp <br/> reg_callback obj; <br/>int luaWrapper_register_callback (lua_State *L) <br/>{ <br/>if (obj. register_callback()) //Not sure what argument to pass here
{
lua_pcall(L,0,0,0);
lua_pushnumber(L,0);
}
return 1;
}
// Lua-script
obj = require(「library」)
local functionTest(f_cMessage)
print(「\ nTesting ........ Test function」,f_cMessage);
end
local register = obj.register_callback(Test());
print(「\ nPrinting:」,寄存器)
這聽起來像[XY問題](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。 –
您的示例程序沒有給出您想要的正確圖片。重載是什麼意思?你想使用函數對象嗎?如果您使用的是簡單的func指針,那麼您隨時都可以從任意位置分配具有不同功能的函數指針。 – Nik
讓我重新分析整個問題。 –