Returning an array of string tables from C to LuaJIT via FFI

I would like the C function to return an array of string tables (e.g. {"a", "b", "c"}) in a Lua script via LuaJIT.

What is the best way to do this?

I thought about returning one concatenated string with some separator (e.g. "a|b|c"), and then split it into Lua, but I was wondering if there is a better way.

EDIT: I am using LuaJIT FFI to call C functions.

+4
source share
2 answers

I think the easiest way to achieve this is to get C code to return a structure containing an array of strings and a length for Lua, and write a little Lua to validate it on the desired data structure.

In C:

typedef struct {
    char *strings[];
    size_t len;
} string_array;

string_array my_func(...) {
    /* do what you are going to do here */
    size_t nstrs = n; /* however many strings you are returning */
    char** str_array = malloc(sizeof(char*)*nstrs);
    /* put all your strings into the array here */
    return {str_array, nstrs};
}

In Lua:

-- load my_func and string_array declarations
local str_array_C = C.ffi.my_func(...)
local str_array_lua = {}
for i = 0, str_array_C.len-1 do
    str_array_lua[i+1] = ffi.string(str_array_C.strings[i])
end
-- str_array_lua now holds your list of strings
+3

C:

 lua_newtable(L);
 lua_pushliteral(L,"a"); lua_rawseti(L,-2,1);
 lua_pushliteral(L,"b"); lua_rawseti(L,-2,2);
 lua_pushliteral(L,"c"); lua_rawseti(L,-2,3);
 return 1;
0

Source: https://habr.com/ru/post/1654448/


All Articles