是否可以让 LuaJIT 进行边界检查?
Is there an option to make LuaJIT do bounds checking?
LuaJIT 知道它定义的 C 类型和数组的长度,但它不检查边界:
ffi = require("ffi")
ten_ints = ffi.typeof("int [10]")
p1 = ten_ints()
print(ffi.sizeof(p1)) -- 40
var_ints = ffi.typeof("int [?]")
p2 = ffi.new(var_ints, 10)
print(ffi.sizeof(p2)) -- 40
p1[1000000] = 1 -- segfault
p2[1000000] = 1 -- segfault
有没有办法让它做到这一点,或者我唯一的选择是编写包装器?
简答:没有办法,你必须write/find你自己的包装器。
这里是luajit.org
的解释
No Hand-holding!
[...] The FFI library provides no memory safety, unlike regular
Lua code. It will happily allow you to dereference a NULL pointer, to
access arrays out of bounds or to misdeclare C functions. If you make
a mistake, your application might crash, just like equivalent C code
would. This behavior is inevitable, since the goal is to provide full
interoperability with C code. Adding extra safety measures, like
bounds checks, would be futile. [...] Likewise there's no way to
infer the valid range of indexes for a returned pointer. Again: the
FFI library is a low-level library.
LuaJIT 知道它定义的 C 类型和数组的长度,但它不检查边界:
ffi = require("ffi")
ten_ints = ffi.typeof("int [10]")
p1 = ten_ints()
print(ffi.sizeof(p1)) -- 40
var_ints = ffi.typeof("int [?]")
p2 = ffi.new(var_ints, 10)
print(ffi.sizeof(p2)) -- 40
p1[1000000] = 1 -- segfault
p2[1000000] = 1 -- segfault
有没有办法让它做到这一点,或者我唯一的选择是编写包装器?
简答:没有办法,你必须write/find你自己的包装器。
这里是luajit.org
的解释No Hand-holding!
[...] The FFI library provides no memory safety, unlike regular Lua code. It will happily allow you to dereference a NULL pointer, to access arrays out of bounds or to misdeclare C functions. If you make a mistake, your application might crash, just like equivalent C code would. This behavior is inevitable, since the goal is to provide full interoperability with C code. Adding extra safety measures, like bounds checks, would be futile. [...] Likewise there's no way to infer the valid range of indexes for a returned pointer. Again: the FFI library is a low-level library.