參考:http://www.swig.org/Doc3.0/SWIGDocumentation.html#Library_std_vector
lua 5.2 / swig 3.08
//example.h
#include <stdio.h>
class example{
public:
example(){
printf("example constructor\n");
}
~example(){
printf("example deconstructor\n");
}
void print(){
printf("hello world!\n");
}
static void add(int num1,int num2)
{
result = num1 + num2;
printf("%d",result);
}
static int result;
}
// derived.h
#include "example.h"
class derived : public example{
public:
derived(){
printf("derived constructor\n");
}
~derived(){
printf("derived deconstructor\n");
}
}
編寫example.i
%module example
%{
#include "example.h"
#include "derived.h"
%}
%include "example.h"
%include "derived.h"
在命令行下使用swig生成lua接口
swig -lua -c++ example.i
此時生成一個example_wrap.cxx的文件
接下來是測試,測試可以將上面的代碼編成庫的形式,也可以直接使用example_wrap.cxx,如
//test.cpp
#include "example_wrap.cxx"
extern "C"{
extern int luaopen_example();
}
int main()
{
lua_State* L = luaL_newstate();
static const luaL_Reg lualibs[]={
{"base",luaopen_base},
{"example",luaopen_example},
{NULL,NULL}
};
const luaL_Reg* lib = lualibs;
for(;lib->func != NULL; lib++)
{
luaL_requiref(L,lib->name,lib->func,1);
lua_pop(L,1);
}
luaL_dofile("test.lua");
return 0;
}
lua文件
--test.lua
d = example.derived()
d:print();
example.example.add(1,3);
print(example.example.result);
這裏需要註明在lua中調用c++各類函數的方式:
1、類成員變量和函數使用類實例加冒號(:)調用,如上
2、靜態成員變量和函數,採用模塊名.類名.變量(或函數)的方式
參考:1、http://www.cnblogs.com/sevenyuan/p/4511808.html
2、http://blog.csdn.net/huangjm_13/article/details/8194075
3、http://blog.csdn.net/u010640235/article/details/52060947