C++ 技术中心

   :: 首页 :: 联系 ::  :: 管理
  160 Posts :: 0 Stories :: 87 Comments :: 0 Trackbacks

公告

郑重声明:本BLOG所发表的原创文章,作者保留一切权利。必须经过作者本人同意后方可转载,并注名作者(天空)和出处(CppBlog.com)。作者Email:coder@luckcoder.com

留言簿(27)

搜索

  •  

最新随笔

最新评论

评论排行榜

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.编写modulehello.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
看到数字表示成员函数被正常调用
posted on 2014-04-24 16:12 C++技术中心 阅读(3302) 评论(0)  编辑 收藏 引用 所属分类: 其他编程

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理