1,lua使用5.1版本,swig-2.0.9还不支持lua5.2
2,下载swig-2.0.9编译安装,会报一个找不到pcre的错误,需要另一个包pcre-8.32.tar.gz(
Perl Compatible Regular Expressions
),先安装这个包3,将swig Example lua下的simple和functest两个例子合并,如下:
// simple.cpp
/* A global variable */
double Foo = 3.0;
/* Compute the greatest common divisor of positive integers */
int gcd(int x, int y) {
int g;
g = y;
while (x > 0) {
g = x;
x = y % x;
y = g;
}
return g;
}
// simple.i
%inline %{
extern double Foo;
extern int gcd(int x, int y);
%}
-- simple.lua
---- importing ----
-- lua 5.1 does
require('example')
-- Call our gcd() function
x = 42
y = 105
g = example.gcd(x,y)
print("The gcd of",x,"and",y,"is",g)
-- Manipulate the Foo global variable
-- Output its current value
print("Foo = ", example.Foo)
-- Change its value
example.Foo = 3.1415926
-- See if the change took effect
print("Foo = ", example.Foo)
// functest.cpp
int add1(int x, int y)
{
return x+y;
}
void add2(int x, int *y, int *z)
{
*z = x+*y;
}
int add3(int x, int y, int *z)
{
*z = x-y;
return x+y;
}
void add4(int x, int *y)
{
*y += x;
}
// functest.i
%include "typemaps.i" // you must have this for the typemaps for ptrs
%inline %{
extern int add1(int x, int y); // return x+y -- basic function test
extern void add2(int x, int *INPUT, int *OUTPUT); // *z = x+*y -- argin and argout test
extern int add3(int x, int y, int *OUTPUT); // return x+y, *z=x-y -- returning 2 values
extern void add4(int x, int *INOUT); // *y += x -- INOUT dual purpose variable
%}
-- functest.lua
---- importing ----
-- lua 5.1 does
require('example')
x,y = 42,105
print("add1 - simple arg passing and single return value -- ")
print(example.add1(x,y))
print("add2 - pointer arg passing and single return value through pointer arg -- ")
print(example.add2(x,y))
print("add3 - simple arg passing and double return value through return and ptr arg -- ")
print(example.add3(x,y))
print("add4 - dual use arg and return value -- ")
print(example.add4(x,y))
-- 最后增加一个接口定义文件example.i,汇总所有*.i文件
%module example
%include "simple.i"
%include "functest.i"
// Makefile文件如下:
all:
swig -c++ -lua example.i
g++ -c -fpic *.cpp *.cxx
g++ -shared *.o -o example.so
clean:
rm -f *.o *.so *_wrap.c *_wrap.cxx
编译:
make
运行:
lua simple.lua,输出如下:
The gcd of 42 and 105 is 21
Foo = 3
Foo = 3.1415926
lua functest.lua,输出如下:
add1 - simple arg passing and single return value --
147
add2 - pointer arg passing and single return value through pointer arg --
147
add3 - simple arg passing and double return value through return and ptr arg --
147 -63
add4 - dual use arg and return value --
147
问题:*.i文件中定义的接口能否自动生成文档?
在*.i文件中用include指令直接包含C/C++的头文件,不用copy函数声明?
SWIG的一般工作流程
编写c/c++程序,编写接口文件(*.i),准备相应的库文件;
用SWIG读取编写描述文件 (*.i) ,生成接口文件 (*_wrap.cxx) ;
将接口文件、需要调用的代码编译为目标文件(.o) ;
将接口文件的目标文件和原代码段的目标文件(还有静态库文件,如果有的话)一起编译成动态库 ;
在lua中调用相应的前面生成的C++动态库文件(.so) 中的接口。