Sandu Liviu Catalin Sandu Liviu Catalin - 2 months ago 14x
C Question

LuaJit FFI Return string from C function to Lua?

Say I have this C function:

__declspec(dllexport) const char* GetStr()
static char buff[32]

// Fill the buffer with some string here

return buff;

And this simple Lua module:

local mymodule = {}

local ffi = require("ffi")

const char* GetStr();

function mymodule.get_str()
return ffi.C.GetStr()

return mymodule

How can I get the returned string from the C function as a Lua string here:

local mymodule = require "mymodule"



The ffi.string function apparently does the conversion you are looking for.

function mymodule.get_str()
    local c_str = ffi.C.GetStr()
    return ffi.string(c_str)

If you are getting a crash, then make sure that your C string is null terminated and, in your case, has at most 31 characterss (so as to not overflow its buffer).