LuaJit FFI Return string from C function to Lua?

廉价感情. 提交于 2020-01-04 05:20:34

问题


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 can I get the returned string from the C function as a Lua string here:

local mymodule = require "mymodule"

print(mymodule.get_str())

回答1:


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

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



来源:https://stackoverflow.com/questions/25597155/luajit-ffi-return-string-from-c-function-to-lua

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!