为了 Lua 的简单性和美观性,我想用 Lua 而不是 C 来编写“映射”代码;-)
假设在 C 语言中我可以有以下内容:
typedef struct my_struct{
char field_1[10];
char field_2[250];
char field_3[2000];
}my_struct;
my_struct *pmy_struct;
pmy_struct = (my_struct *) some_buffer;
所以我想在Lua中找到一种方法,在“结构”内的字段上有固定的长度,以便整体缓冲区偏移量在到达目标系统时保持完好......
所以可以说,在上面的结构中,我想将“field_3”设置为文本“apple”……我仍然希望该结构字段的总长度为 2000 字节……
你可以用 Lua 来做到这一点。
如果您希望(或被迫)继续使用 Lua 5.1,请考虑使用struct http://www.inf.puc-rio.br/~roberto/struct/图书馆。
raw_data = struct.pack("c10c250c2000", field1, field2, field3)
field1, field2, field3 = struct.unpack("c10c250c2000", raw_data)
不过,目前最好的解决方案是LuaJIT http://luajit.org/luajit.html;与标准 Lua 实现相比,使用 LuaJIT 有很多好处,但最适合您的是外国金融机构图书馆 http://luajit.org/ext_ffi.html.
local ffi = require"ffi"
ffi.cdef[[
typedef struct {
char field_1[10];
char field_2[250];
char field_3[2000];
} my_struct;
]]
local my_thing = ffi.new("my_struct")
my_thing.field_1 = "Ain't"
my_thing.field_2 = "this"
my_thing.field_3 = "great? :D"
local ptr_my_thing = ffi.new("my_struct*", my_thing)
ptr_my_thing.field_2 = [[
LuaJIT does a great job at figuring out
what you're trying to do.
]]
ptr_my_thing.field_3 = [[
There are some cases where the generics of
Lua cannot be used to infer information,
so have a look at the LuaJIT site for specifics.
]]
print(ffi.string(ptr_my_thing.field_2))
一种常见的误解是,诸如 Lua 和 Python 之类的通用语言不应该(或者在无知的情况下不能)用于低级细节。
LuaJIT 是“智能”语言的重要第一步,它允许您在任何级别上工作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)