luajit笔记---编译成静态库以及FFI绑定宿主程序函数

转自:http://blog.csdn.net/fg5823820/article/details/8888207

本以为可以像lua一样把代码丢进去直接编译就好了,结果发现luajit有一堆汇编代码,不知道怎么处理,后来一搜索才知道luajit本身提高的批处理也可以编译成静态库,就是在后面加个static,郁闷到了。http://blog.csdn.NET/whitehack/article/details/6451293


Google来Google,终于看到用FFI绑定宿主程序函数的例子,卧槽,知道真相我的眼泪都流下来!原来FFI本质是绑定导出的符号,所以说只要导出符号就可以用,吐血。

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include <lua.hpp>  
  2.   
  3. #include <cassert>  
  4.   
  5. // Please note that despite the fact that we build this code as a regular  
  6. // executable (exe), we still use __declspec(dllexport) to export  
  7. // symbols. Without doing that FFI wouldn't be able to locate them!  
  8.   
  9. extern "C"   
  10. {  
  11.     __declspec(dllexportvoid __cdecl hello_from_lua(const char *msg)  
  12.     {  
  13.         printf("A message from LUA: %s\n", msg);  
  14.     }  
  15.     __declspec(dllexportint  Add(int a,int b)  
  16.     {  
  17.         return a+b;  
  18.     }  
  19. }  
  20.   
  21. const char *lua_code =  
  22. "local ffi = require('ffi')                   \n"  
  23. "ffi.cdef[[                                   \n"  
  24. "const char * hello_from_lua(const char *);   \n" // matches the C prototype  
  25. "int Add(int,int);"  
  26. "]]                                           \n"  
  27. "ffi.C.hello_from_lua('Hello from LUA!')      \n" // do actual C call  
  28. "sum = ffi.C.Add(10,20)      \n"  
  29. "print('sum:'..sum)      \n"  
  30. ;  
  31.   
  32. int main()  
  33. {  
  34.     lua_State *lua = luaL_newstate();  
  35.     assert(lua);  
  36.     luaL_openlibs(lua);  
  37.   
  38.     const int status = luaL_dostring(lua, lua_code);  
  39.     if(status)  
  40.         printf("Couldn't execute LUA code: %s\n", lua_tostring(lua, -1));  
  41.   
  42.     lua_close(lua);  
  43.     return 0;  
  44. }  

另外发现,就算是导出了符号,FFI也只能对本程序的导出符号进行绑定,比如我在一个DLL里面导出了符号,虽然宿主程序使用了这个DLL,但是依然没法绑定。

后来看了luajit官网,发现lua51.dll里面的函数在FFI是可用的,至于他们怎么做到我就不清楚了,只能说有可能可以做到这一点。这种黑科技果然不是那么热就能掌握的,而且关于luajit,感觉资料实在太少了,说实在其实lua 的资料本身就少了


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值