如果像我这样的其他人对上面附加帖子中的答案感到困惑,这里是一个将 Lua 表传递给 C 库的完整工作示例。
关键是要知道 Lua 中的数字是 C 中的双精度数
如果这不是最佳解决方案,我相信有人会告诉我/我们!
--Lua 代码,v5.4.3 使用 Ubuntu 21.10
#!/usr/bin/env -S lua -W
-- Require cffi-lua, not from luaJIT
-- via LuaRocks, with LUA_CPATH set
local cffi = require("cffi")
-- Load libfoo
local mylib = cffi.load('./libfoo.so')
-- Function prototype definitions
cffi.cdef [[
//int gettable(const char *file, const char **datav); //Original
int getStable(const char **data);
int getItable(const double *data, int size);
]]
-- Main program ------------------------------------
print("Test Program!")
local data1 = cffi.new("const char*[3]", {"ls", "-lsdfsdf"}) --original, works
--from a Lua Table
local mytableS = {"string one", "string two", "string three"}
local mytableSlen = #mytableS
local mytableSCstruct = "const char*[" .. mytableSlen + 1 .. "]"
local mytableSCuserdata = cffi.new(mytableSCstruct, mytableS)
print(type(mytableSCuserdata))
local ret = mylib.getStable(mytableSCuserdata)
print(ret)
--from a Lua Table, where it is necessary to know that Lua Numbers
-- are Doubles in C
local mytableI = {12,23,34,45,56,67,78,89,91,120, 3.142, 2.71828}
local mytableIlen = #mytableI
local mytableICstruct = "const double[" .. mytableIlen .. "]"
local mytableICuserdata = cffi.new(mytableICstruct, mytableI)
print(type(mytableICuserdata))
local ret = mylib.getItable(mytableICuserdata, mytableIlen)
print(ret)
print("Bye!")
C 库代码,编译时使用
gcc foo.c -shared -fPIC -std=c11 -o libfoo.so
/***************************************
library
***************************************/
#include <stdio.h>
#include <stdlib.h>
//Using Strings
int getStable(const char **data)
{
printf("In S GetTable\n");
for (const char **item = data; *item; ++item)
{
printf("Processing Item: %s\n", *item);
}
//not used
return 0;
}
//Using Doubles
int getItable(const double *data, int size)
{
printf("In I GetTable, with size: %d\n", size);
for (int i = 0; i < size; i++)
{
printf("Processing Item: %lf\n", data[i]);
}
//not used
return 0;
}