LuaJit FFI从C函数返回字符串到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个字符(以便不溢出其缓冲区)。