Search code examples
carrayslualuajit

How to print a fixed array of char in LuaJIT?


I'm trying to print the contents of a null terminated string that is stored in a fixed array. The array is memset'd to zero at the start and then is populated with a null terminated string. I'm attempting to print the string.

This works:

ffi.cdef[[
typedef struct _t
{
    uint16_t i;
    const char * name;
} MyStruct;
]]

ffi.cdef[[
MyStruct* Get();
]]

local myDll = ffi.load("myDll")
local x = myDll.Get()
print("Name: %s", x.name)

This results in an error:

ffi.cdef[[
typedef struct _t
{
    uint16_t i;
    char name[25];
} MyStruct;
]]

ffi.cdef[[
MyStruct* Get();
]]

local myDll = ffi.load("myDll")
local x = myDll.Get()
print("Name: %s", x.name)

The second produces this error:

27: bad argument #2 to 'print' (cannot convert 'char [25]' to 'char (&)[25]')

NOTE: Code was edited from original for this posting without compiling it.

It seems I am improperly handling the array. What is the correct way to do this?


Solution

  • You can't print c-strings directly with the print function. You need to either convert it to a Lua string first or use the C printf function

    print("Name: ", ffi.string(x.name))
    

    or

    ffi.C.printf("Name: %s", x.name) -- Note: need to cdecl printf first