Search code examples
cluaffiluajit

How do I convert a lua string to a C char*?


I've used the luajit ffi library to wrap a C library that contains a function to draw text on a ppm file:

void drawText(frameBuffer *fb, int px, int py, char* text, pixel color) 

When I try to call it from lua using a string I get this error bad argument #4 to 'drawText' (cannot convert 'string' to 'char *'). It doesn't look like the lua string library has anything to convert entire strings to byte arrays or anything that I could manipulate sufficiently.

Any tips on how I could do this on the lua side without modifying the C code?


Solution

  • You cannot pass a Lua string to a ffi function that expects a char* directly. You need to convert the Lua string to a char* first. To do so, create a new C string variable with ffi.new and after that copy the content of your Lua string variable to this new C string variable. For instance:

    local text = "text"
    -- +1 to account for zero-terminator
    local c_str = ffi.new("char[?]", #text + 1)
    ffi.copy(c_str, text)
    lib.drawText(fb, px, py, c_str, color)