Search code examples
cluaffiluajit

LuaJIT ffi : How to pass array of string to c function


I want to pass Lua table storing strings to c function. So for example if I have

tStr = {"String1", "String2", "String3"}

How do I pass to C function. I think I have to call ffi.new but which what type I am not sure..

local cVar = ffi.new("??" , tStr)  -- I am not sure what to pass as type 

parameter

Also in C Function, I am not sure how to access the whole data, will it be string pointer pointing to string , **str ??

void cFunction(**str); --What pointer type should be used here ??

... Apologies if I missed something obvious question. But I am just starting with Lua & ffi. so I am still not aware of most of the things ..


Solution

  • This is a simple example:

    local ffi = require"ffi"
    ffi.cdef"int execvp(const char*file, const char**argv);"
    local arg = ffi.new("const char*[3]", {"ls", "-l"})
    ffi.C.execvp(arg[0], arg)
    

    Please note that constant 3 (size of the array)
    equals to 2 (the number of strings passed from Lua {"ls", "-l"})
    plus 1 (last element in the array is actually a zero-terminator).