LuaJit FFI 如何将 C 函数返回的字符串传递到 Lua 中?

假设我有这个 C 函数:

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

    // 在此处用一些字符串填充缓冲区

    return buff;
}

以及这个简单的 Lua 模块:

local mymodule = {}

local ffi = require("ffi")

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

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

return mymodule

如何将从 C 函数返回的字符串作为 Lua 字符串在这里获取:

local mymodule = require "mymodule"

print(mymodule.get_str())
点赞
用户90511
用户90511

ffi.string 函数显然可以完成你要寻找的转换。

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

如果你遇到了崩溃问题,那么请确保你的 C 字符串以空字符结尾,并且在你的情况下最多有 31 个字符(以免溢出其缓冲区)。

2014-08-31 23:37:22