标签:
一直知道cocos2dx lua是通过tolua++导出lua接口的,但一直没自己去导过,最近比较闲,试了下。
我的环境是:ubuntu ,安装好tolua++后就可以在命令行下试用 tolua++ 工具导出。
MyClass.cpp文件:
#include <iostream>
#include "tolua++.h"
class MyClass
{
public:
void say()
{
std::cout << "Hello World!" << std::endl;
}
};
tolua++需要写pkg文件,类似于C++的.h文件,当时要过去掉关键字,MyClass.pkg
#include "MyClass.h"
class MyClass
{
MyClass();
~MyClass();
void say();
};
在终端执行:
tolua++ -o MyClass.cpp MyClass.pkg //-o MyClass.cpp 表示写入MyClass.cpp 文件。
执行完后,会生成MyClass.cpp文件,打开会发现有好几百行代码,会有一个
TOLUA_API int luaopen_MyClass (lua_State* tolua_S)
的定义,然后在该文件中加入对MyClass.h文件的引用:
#include "string.h" #include "tolua++.h" ... #include "MyClass.h" ... TOLUA_API int luaopen_MyClass (lua_State* tolua_S) //该方法就是要导出到lua的方法
在MyClass.h文件中增加函数声明:
/* Exported function */ TOLUA_API int tolua_MyClass_open (lua_State* tolua_S);
mytest.lua测试文件:
local my = MyClass() my:say()
通过main.cpp 文件来执行lua。
#include <iostream>
#ifdef __cplusplus
extern "C" { #endif
#include "tolua++.h"
#ifdef __cplusplus
}
#endif
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
#include "MyClass.h"
TOLUA_API int tolua_MyClass_open (lua_State* tolua_S);
int main()
{
lua_State* L = lua_open();
luaL_openlibs(L);
tolua_MyClass_open(L);
luaL_dofile(L, "mytest.lua"); // 执行lua脚本文件
lua_close(L);
return 0;
}
在终端输入:
g++ main.cpp MyClass.cpp -llua -ldl -ltolua++ -o test_lua
-lxx为g++的编译规则,表示需要链接的库文件。
结果就会打印出:hello world
标签:
原文地址:http://my.oschina.net/u/156466/blog/402114