织梦CMS - 轻松建站从此开始!

罗索

让c++与lua互操作

jackyhwei 发布于 2011-06-15 21:07 点击:次 
首先封装一个类lua_wrapper,供需要向lua暴露接口的c++类继承
TAG:

首先封装一个类lua_wrapper,供需要向lua暴露接口的c++类继承:

  1. extern "C" { 
  2. #include <lua.h> 
  3. #include <lua.hpp> 
  4. #include <lauxlib.h> 
  5. #include <luaconf.h> 
  6. #include <lualib.h> 
  7. class lua_wrapper 
  8.     typedef int (*fun_cpp_api)(lua_State* luaState); 
  9. private
  10.     static lua_State *s_lua_ptr; 
  11.      
  12.     map<string, fun_cpp_api> m_map_api; 
  13. public
  14.     static bool lua_base_init() 
  15.     { 
  16.         if (s_lua_ptr = NULL) { 
  17.             s_lua_ptr = lua_open(); 
  18.             if (s_lua_ptr != NULL) { 
  19.                 luaopen_base(s_lua_ptr); 
  20.                 luaopen_table(s_lua_ptr); 
  21.                 luaopen_string(s_lua_ptr); 
  22.                 luaopen_math(s_lua_ptr); 
  23.                 return true
  24.             } 
  25.         } 
  26.          
  27.         return false
  28.     } 
  29.      
  30.     int Call(const string fun_name, lua_State* luaState) 
  31.     { 
  32.         map<string, fun_cpp_api>::const_iterator iter = 
  33.             m_map_api.find(fun_name); 
  34.              
  35.         if (iter == m_map_api.end()) { 
  36.             return -1; 
  37.         } 
  38.          
  39.         return (iter->second)(luaState); 
  40.     } 
  41.      
  42. #define API_ADD_FUN(fun) do { \ 
  43.         m_map_api[#fun] = fun; \ 
  44.         setfield(#fun, fun); \ 
  45.     } while(0) 
  46. #define BEGIN_FUNCTION_MAP(x) \ 
  47.     lua_newtable(s_lua_ptr); \ 
  48.     API_ADD_FUN(Call); \ 
  49.     API_ADD_FUN(AttachListener);  \ 
  50.     API_ADD_FUN(DetachListener);  
  51. }; 

 

(shuizhiyun)
本站文章除注明转载外,均为本站原创或编译欢迎任何形式的转载,但请务必注明出处,尊重他人劳动,同学习共成长。转载请注明:文章转载自:罗索实验室 [http://www.rosoo.net/a/201106/14566.html]
本文出处:CSDN博客 作者:shuizhiyun
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片
栏目列表
将本文分享到微信
织梦二维码生成器
推荐内容