LuaJit FFI Returns a string from C to Lua function?

Let's 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")

ffi.cdef[[
    const char* GetStr();
]]

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

return mymodule

      

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

local mymodule = require "mymodule"

print(mymodule.get_str())

      

+3


source to share


1 answer


The function ffi.string

appears to be performing the conversion you are looking for.

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

      



If you get a crash, make sure your C string is null terminated and in your case has no more than 31 characters (so as not to overflow its buffer).

+5


source







All Articles