3

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 ..

1 Answer 1

5

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).

Sign up to request clarification or add additional context in comments.

3 Comments

You'll probably need to anchor {"ls", "-l"} to a variable so lua doesn't gc it prematurely. const char* is going to keep a pointer into those string literals in the table.
@greatwolf - In general, yes, one must keep references to strings alive. But string literals are automatically kept alive as long as the function containing it (actually its prototype) is not garbage collected.
This worked for me.. Also, I just came across the fact that, if we don't want to allocate fixed size array then we can use VLA using "const char *[?]" syntax and then passing number of elements..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.