原始代码
local ffi = require("ffi")
ffi.cdef[[
struct timeval {
long int tv_sec;
long int tv_usec;
};
int gettimeofday(struct timeval *tv, void *tz);
]];
local gettimeofday_struct = ffi.new("struct timeval")
local function gettimeofday()
ffi.C.gettimeofday(gettimeofday_struct, nil)
return tonumber(gettimeofday_struct.tv_sec) * 1000000 + tonumber(gettimeofday_struct.tv_usec)
end
运行报错
[error] 4028#0: *5 lua entry thread aborted: runtime error: /opt/olwaf/olaccess.lua:126: attempt to redefine 'timeval' at line 2
stack traceback:
coroutine 0:
[C]: in function 'cdef'
/opt/olwaf/olaccess.lua:126: in main chunk, client: 127.0.0.1, server: www.olwaf.com, request: "POST /api/v2/dict_info HTTP/1.1", host: "www.olwaf.com"
修改后正常
local ffi = require("ffi")
if pcall(ffi.typeof, "struct timeval") then
-- check if already defined.
else
ffi.cdef[[
typedef struct timeval {
long tv_sec;
long tv_usec;
} timeval;
int gettimeofday(struct timeval* t, void* tzp);
]]
end
local gettimeofday_struct = ffi.new("struct timeval")
local function gettimeofday()
ffi.C.gettimeofday(gettimeofday_struct, nil)
return tonumber(gettimeofday_struct.tv_sec) * 1000000 + tonumber(gettimeofday_struct.tv_usec)
end
这篇博客讨论了在Lua中使用FFI( Foreign Function Interface )库时遇到的类型重定义错误。原始代码尝试定义已存在的`struct timeval`导致运行时错误。为了解决这个问题,修改后的代码首先检查类型是否已定义,如果未定义则进行cdef,确保不会重复定义。这个例子展示了在使用FFI时如何优雅地处理类型定义,以避免冲突。

1139

被折叠的 条评论
为什么被折叠?



