Use swig + lua quick guide

软件
swigwin3    用于生成c的lua包装
lua5.2源代码

步骤
进入目录G:\sw\swigwin-3.0.12\Examples\lua\arrays
执行 SWIG -lua     example.i, 就会生成文件example_wrap.c
进入lua source code G:\doc\lua\lua-5.2.4.tar\lua-5.2.4\src
拷贝swig生成的几个c文件到该目录

b编写一个新的mymain.c内容如下

执行cl编译生成example.exe

执行example.exe runme.lua

 

代码:

===example.i

/* File : example.i */
%module example

/* in this file there are two sorting functions
and three different ways to wrap them.

See the lua code for how they are called
*/

%include <carrays.i>    // array helpers

// this declares a batch of function for manipulating C integer arrays
%array_functions(int,int)

// this adds some lua code directly into the module
// warning: you need the example. prefix if you want it added into the module
// admittedly this code is a bit tedious, but its a one off effort
%luacode {
function example.sort_int2(t)
-- local len=table.maxn(t) -- the len - maxn deprecated in 5.3
 local len=0; for _ in pairs(t) do len=len+1 end
 local arr=example.new_int(len)
 for i=1,len do
  example.int_setitem(arr,i-1,t[i]) -- note: C index is one less then lua index
 end
 example.sort_int(arr,len) -- call the fn
 -- copy back
 for i=1,len do
  t[i]=example.int_getitem(arr,i-1) -- note: C index is one less then lua index
 end
 example.delete_int(arr) -- must delete it
end
}

// this way uses the SWIG-Lua typemaps to do the conversion for us
// the %apply command states to apply this wherever the argument signature matches
%include <typemaps.i>
%apply (double *INOUT,int) {(double* arr,int len)};

%inline %{
extern void sort_int(int* arr, int len);
extern void sort_double(double* arr, int len);
%}

===runme.lua

---- importing ----
if string.sub(_VERSION,1,7)=='Lua 5.0' then
    -- lua5.0 doesnt have a nice way to do this
    lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example')
    assert(lib)()
else
    -- lua 5.1 does
    require('example')
end

-- a helper to print a Lua table
function print_table(t)
    print(table.concat(t,","))
end

-- a helper to print a C array
function print_array(arr,len)
    for i=0,len-1 do
        io.write(example.int_getitem(arr,i),",")
    end
    io.write("\n")
end

math.randomseed(0)  -- init random


--[[ version 1: passing a C array to the code
let's test call sort_int()
this requires a C array, so is the hardest to use]]
ARRAY_SIZE=10
arr=example.new_int(ARRAY_SIZE)
for i=0,ARRAY_SIZE-1 do
    example.int_setitem(arr,i,math.random(1000))
end
print "unsorted"
print_array(arr,ARRAY_SIZE)
example.sort_int(arr,ARRAY_SIZE)
print "sorted"
print_array(arr,ARRAY_SIZE)
example.delete_int(arr) -- must delete it
print ""

--[[ version 2: using %luacode to write a helper
a simpler way is to use a %luacode
which is a lua function added into the module
this can do the conversion for us
so we can just add a lua table directly
(what we do is move the lua code into the module instead)
]]
t={}
for i=1,ARRAY_SIZE do
    t[i]=math.random(1000)
end
print "unsorted"
print_table(t)
example.sort_int2(t) -- calls lua helper which then calls C
print "sorted"
print_table(t)
print ""

--[[ version 3: use a typemap
this is the best way
it uses the SWIG-Lua typemaps to do the work
one item of note: the typemap creates a copy, rather than edit-in-place]]
t={}
for i=1,ARRAY_SIZE do
    t[i]=math.random(1000)/10
end
print "unsorted"
print_table(t)
t=example.sort_double(t) -- replace t with the result
print "sorted"
print_table(t)

===mymain.c

#include <stdio.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

extern int luaopen_example(lua_State* L); // declare the wrapped module

int main(int argc, char* argv[])
{
 lua_State *L;
 if (argc<2)
 {
  printf("%s: <filename.lua>\n", argv[0]);
  return 0;
 }
 L= luaL_newstate();
 luaL_openlibs(L);
 //luaopen_base(L);       // load basic libs (eg. print)
 //luaopen_math(L);
 luaopen_example(L);    // load the wrapped module
 if (luaL_loadfile(L, argv[1])==0) // load and run the file
  lua_pcall(L, 0, 0, 0);
 else
  printf("unable to load %s\n", argv[1]);
 lua_close(L);
 return 0;
}

 

结果:

 

参考:

file:///G:/sw/swigwin-3.0.12/Doc/Manual/Lua.html#Lua_nn2

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
详细描述Lua和C之间相互传递Table类型数据 /* ====================================================== */ // 遍历Lua传入的Table类型参数, 获取它的Key/Value, 其关键操作是 lua_next() // lua_next() 返回1表示读取成功,返回0表示已经没有数据可读了 // lua_next() 会使用栈顶元素作为Key去定位本次需要取出Table里面的那个值对 // 如果Key=nil, 那就表示本次取出的是第一个元素 // 它会先将当前的这个Key弹出,然后将本次取出的Key/Value压入栈, Value在栈顶 // 一个比较隐晦的处理就是, 我们不应直接使用lua_tostring(L, -2)来读取Key // 因为lua_tostring()在Key类型不是字符串时, 它会修改栈上的Key数据 // 这样, 下次调用lua_next()时, 就会因为Key被修改了而导致错误 // 为此,先调用lua_pushvalue(L, -2),将它Copy一份到栈顶,对这个Copy进行lua_tostring() // 读取Key,Value到C变量里面后,将Value和Copy弹出,留着Key在栈顶,给下次lua_next()用 // // 指令及栈图变化如下: (假如Table的栈下标是Index) // 0. 刚进入函数时 ...Table, ... <--- 这里栈顶 // 1. lua_pushnil(L) ...Table, ..., nil <--- 这里栈顶 // 2. lua_next(L, Index) ...Table, ..., Key, Value <--- 这里栈顶 // 3. lua_pushvalue(L, -2) ...Table, ..., Key, Value, KeyCopy <--- 这里栈顶 // 4. lua_pop(L, 2), ...Table, ..., Key <--- 这里栈顶 // ... 如此重复2,3,4 // N. lua_next(L, Index)返回0 ...Table, ... <--- 这里栈顶 /* ====================================================== */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值