LuaJit FFI从C函数返回字符串到Lua吗? [英] LuaJit FFI Return string from C function to Lua?
本文介绍了LuaJit FFI从C函数返回字符串到Lua吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有这个C函数:
__declspec(dllexport) const char* GetStr()
{
static char buff[32]
// Fill the buffer with some string here
return buff;
}
这个简单的Lua模块:
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
如何在这里从C函数获取返回的字符串作为Lua字符串:
How can I get the returned string from the C function as a Lua string here:
local mymodule = require "mymodule"
print(mymodule.get_str())
推荐答案
ffi.string
函数显然可以完成您要寻找的转换.
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
如果遇到崩溃,请确保您的C字符串以null终止,并且在您的情况下,最多包含31个字符(以免缓冲区溢出).
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).
这篇关于LuaJit FFI从C函数返回字符串到Lua吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文