利用c++与swig+lua

利用c++与swig+lua
1.下载swig,我这里用的是 swigwin-2.0.9.zip,官网地址 http://www.swig.org/ 载解压后,目录下有swig.exe程序
2. 在VS中新建工程TestLua
3.添加hello.h代码如下:
#ifndef HELLO_H__
#define HELLO_H__

int sum(  int a,  int b );
class Test
{
public:
     int a;
     int b;
    Test();
     void print();
};

#endif/*HELLO_H__*/

4.添加hello.cpp代码如下:
#include "stdafx.h"
#include "hello.h"

int sum(  int a,  int b )
{
     return (a + b);
}
Test::Test()
{
    a = 10;
    b = 20;
}
void Test::print()
{
    printf( "%d %d\n", a, b );
}

5.编写moduleh ello.i文件,内容如下:
%module hello
%{
#include "hello.h"
%}
%include "hello.h"

6.使用以下命令生成文件
swig.exe -c++ -lua c:\modulehello.i
于是生成: modulehello_wrap.cxx文件

7.在工程包含
C:\Program Files (x86)\Lua\5.1\include
符加库目录 "C:\Program Files (x86)\Lua\5.1\lib"
并且导入库
lua51.lib

8.在工程文件TestLua.cpp代码如下:
#include "stdafx.h"
extern "C"
{
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
};
#include "modulehello_wrap.cxx"
extern "C"
{
     extern  int luaopen_hello(lua_State* L);  //  declare the wrapped module
};
int _tmain( int argc, _TCHAR* argv[])
{
    lua_State *L;
    L=lua_open();
    luaopen_base(L);     //  load basic libs (eg. print)
    luaopen_hello(L);     //  load the wrappered module
     if (luaL_loadfile(L,"./hello.lua")==0)  //  load and run the file
        lua_pcall(L,0,0,0);
     else
        printf("unable to load %s\n","hello.lua");
    lua_close(L);

     return 0;
}

9.编写lua脚本hello.lua如下:
print( "测试脚本是否被调用" );
print( "hello" );
print( "hello, tpf" );
print( "看到hello的字样,表示脚本被调用" );

print( "-----------------------------" );

print( "下面测试函数" );
print( hello.sum( 1, 2 ) );
print( "看到数字表示函数正常被调用" );

print( "-----------------------------" );

print( "下面测试类调用" );
a = hello.Test();

print( "-----------------------------" );
print( "成员变量>>>", a.a );
print( "成员变量>>>", a.b );

print( "下面测试成员函数" );
a:print();
print( "看到数字表示成员函数被正常调用" );

10.得出结果如下:
测试脚本是否被调用
hello
hello, tpf
看到hello的字样,表示脚本被调用
-----------------------------
下面测试函数
3
看到数字表示函数正常被调用
-----------------------------
下面测试类调用
-----------------------------
成员变量>>>     10
成员变量>>>     20
下面测试成员函数
10 20
看到数字表示成员函数被正常调用

你可能感兴趣的:(利用c++与swig+lua)