lua中调用C++函数

我们产品中提供了很多lua-C API给用户在lua中调用,之前一直没用深究其实现原理,只是根据已有的代码在编码。显然这不是一个好的习惯,没用达到知其所以然的目的。

一、基本原理

将C++函数编译成动态链接库,然后在lua中require,通过下面的示例进行详解。

#ifdef __cplusplus
extern "C" {
#endif
#include<lua.h>
#include<lualib.h>
#include<lauxlib.h>
#ifdef __cplusplus
}
#endif static int add (lua_State *L)
#ifdef __cplusplus
extern "C" {
#endif
#include<lua.h>
#include<lualib.h>
#include<lauxlib.h>
#ifdef __cplusplus
}
#endif
/**
要写一个lua中可以调用的函数,一般需要三个步骤,
第一步:定义函数,而且要遵守一定的规则,即
参数只能有一个(lua_State*),返回值也只能为
整型int,本例中static关键字可以不写。
*/
static int add (lua_State *L)
{
double op1 = lua_tonumber(L, -1);
double op2 = lua_tonumber(L, -2);
lua_pushnumber(L, op1+op2);
return 1;
} /**
第二步:列出所有的本模块中供lua调用的函数,为下
面的注册做准备
*/
static luaL_Reg myfuncs[] = {
{"add", add},
{NULL, NULL}
}; /**
第三步:注册函数到一个lua table中去。
*/
extern "C" int luaopen_mytestlib(lua_State *L)
{
luaL_register(L, "mytestlib", myfuncs);
return 1;
}

二、编译

$ g++ lua_call_cplusplus_function.cc -o mytestlib.so -shared -fPIC -I /usr/include/lua5.1/

三、运行结果

$ lua
Lua 5.1.5 Copyright (C) 1994-2012 Lua.org, PUC-Rio
> require("mytestlib")
> print(mytestlib.add(1,2))
3

四、注意事项

  • luaL_register在lua5.2中被移除了,如果使用lua5.3编译会报如下错误
$ g++ mytestlib.cc -o test.so -shared -fPIC -I /home/wuman/下载/lua-5.3.2/src
mytestlib.cc: In function ‘int luaopen_test(lua_State*)’:
mytestlib.cc:21:34: error: ‘luaL_register’ was not declared in this scope
luaL_register(L, "test", testlib);
  • luaopen_mytestlib这个 extern "C"是必须的,否则require时会报错:
$ lua
Lua 5.1.5 Copyright (C) 1994-2012 Lua.org, PUC-Rio
> require("mytestlib")
error loading module 'mytestlib' from file './mytestlib.so':
./mytestlib.so: undefined symbol: luaopen_mytestlib
stack traceback:
[C]: ?
[C]: in function 'require'
stdin:1: in main chunk
[C]: ?

最新文章

  1. 2016 华南师大ACM校赛 SCNUCPC 非官方题解
  2. 外接Hdmi没有声音怎么设置
  3. JS 中 Array.slice() 和 Array.splice()方法
  4. mysql集群数据一致性校验
  5. lecture11-hopfiled网络与玻尔兹曼机
  6. python调用ggsci.exe程序
  7. jquery validate ajax submit form
  8. Delphi单元文件之-防止程序重复执行
  9. Unity3D脚本中文系列教程(十七)
  10. centos 6.5安装esx sdk
  11. Decorators and Wrappers in Python
  12. 菜鸟学习SSH(二)——Struts国际化
  13. JAVA web四个属性的范围汇总
  14. 百度地图SDK for Android v2.1.3全新发布
  15. 安卓---apk反编译
  16. 浙大pat1042题解
  17. MySQL学习笔记(一)&mdash;数据库基础
  18. Devops step by step
  19. 本机是wifi,虚拟机无法连接外网问题
  20. 简介 - PMP(Project Management Professional)

热门文章

  1. Memcache 一些经验和技巧
  2. 获得IP地址中文
  3. 几个月来使用mobx代替redux的一些总结
  4. vue-cli webpack配置中 如何启动less-loader sass-loader
  5. 谁说NTFS不支持UEFI启动的?启动U盘放不了超过4G的文件怎么办?Server2016 Win10 U盘UEFI启动制作方法
  6. 进程线程之pid,tid
  7. 清空chrome浏览器缓存
  8. HDU 4630 No Pain No Game (线段树+离线)
  9. jquery中的jsonp跨域调用
  10. React:关于虚拟DOM(Virtual DOM)