attempt to redefine ‘timeval‘ at line 2解决办法

这篇博客讨论了在Lua中使用FFI( Foreign Function Interface )库时遇到的类型重定义错误。原始代码尝试定义已存在的`struct timeval`导致运行时错误。为了解决这个问题,修改后的代码首先检查类型是否已定义,如果未定义则进行cdef,确保不会重复定义。这个例子展示了在使用FFI时如何优雅地处理类型定义,以避免冲突。

原始代码

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值