2017-03-09 24 views
0

我正在開發一個庫。我想在庫中使用回調函數來註冊將從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:」,寄存器)

+3

這聽起來像[XY問題](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。 –

+1

您的示例程序沒有給出您想要的正確圖片。重載是什麼意思?你想使用函數對象嗎?如果您使用的是簡單的func指針,那麼您隨時都可以從任意位置分配具有不同功能的函數指針。 – Nik

+0

讓我重新分析整個問題。 –

回答

-3

「Wireshark」(packet-gsm_a_rp.c)的示例。

guint16 (*rp_elem_fcn[])(tvbuff_t *tvb, proto_tree *tree, packet_info *pinfo, guint32 offset, guint len, gchar *add_string, int string_len) = { 
/* Short Message Service Information Elements [5] 8.2 */ 
de_rp_message_ref, /* RP-Message Reference */ 
de_rp_orig_addr, /* RP-Originator Address */ 
de_rp_dest_addr, /* RP-Destination Address */ 
de_rp_user_data, /* RP-User Data */ 
de_rp_cause,  /* RP-Cause */ 
NULL, /* NONE */ 
}; 
static guint16 de_rp_message_ref(tvbuff_t *tvb, proto_tree *tree, packet_info *pinfo _U_, guint32 offset, guint len _U_, gchar *add_string _U_, int string_len _U_) 
{ 
guint32 curr_offset; 

curr_offset = offset; 

proto_tree_add_item(tree, hf_gsm_a_rp_rp_message_reference, tvb, curr_offset, 1, ENC_BIG_ENDIAN); 

curr_offset++; 

/* no length check possible */ 

return(curr_offset - offset); 
} 
+0

雖然此代碼片段可能會解決問題,但[包括解釋](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 –

相關問題