如何在C ++库文件中使用回调函数?

时间:2017-03-09 05:32:45

标签: c++ callback function-pointers libraries

我正在开发一个库。我想在库中使用回调函数来注册将从Lua环境调用的事件。我的库具有所有较低层功能(在文件-reg_callback.cpp& reg_callback.h中)。所有更高层的功能都将在Lua环境中(Lua脚本)。

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);                
}                 
返回1;
}▼Lua-script
obj = require(&#34; library&#34;)
local functionTest(f_cMessage)
print(&#34; \ nTesting ........ Test function&#34;,f_cMessage);
结束
本地寄存器= obj.register_callback(Test());
打印(&#34; \ n打印:&#34;,注册)

1 个答案:

答案 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);
}