[英]LuaJit FFI Return string from C function to Lua?
說我有這個C函數:
__declspec(dllexport) const char* GetStr()
{
static char buff[32]
// Fill the buffer with some string here
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())
ffi.string
函數顯然可以執行您要查找的轉換。
function mymodule.get_str()
local c_str = ffi.C.GetStr()
return ffi.string(c_str)
end
如果您遇到崩潰,請確保您的C字符串為空終止,並且在您的情況下,最多包含31個字符(以便不會溢出其緩沖區)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.