lua require("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 tm = ffi.new("struct timeval");

运行之后报下面的错:

2018/11/19 08:53:55 [error] 24046#0: init_worker_by_lua_file error: lua/ngx_base/resty/utils/time/time_help.lua:24: attempt to redefine 'timeval'
stack traceback:
    [C]: in function 'cdef'
    lua/ngx_base/resty/utils/time/time_help.lua:24: in main chunk
    [C]: in function 'require'
    lua/ngx_base/resty/utils/incr_help.lua:15: in main chunk
    [C]: in function 'require'
    ...s/trade/third_party_union_payment/model/trade_tf_dao.lua:30: in main chunk
    [C]: in function 'require'
    lua/modules/trade/task/trade_task.lua:14: in main chunk
    [C]: in function 'require'
    lua/ngx_base/server/sys_task.lua:11: in function 'init_task'
    lua/ngx_base/server/sys.lua:13: in function 'init'
    ./lua/init_worker_by_lua.lua:16: in main chunk
阅读 4.7k
1 个回答

问题原因:我安装了luarocks install lua-resty-uuid之后,这个文件里面有timeval的定义,所以会报错!
解决办法:
1、卸载 luarocks remove lua-resty-uuid
2、使用如下方式

一个解决的办法是总是使用 ffi.typeof 函数在定义前进行存在性测试,例如

    local ffi = require "ffi"
    if pcall(ffi.typeof, "struct in_addr") then
        -- already defined! do nothing here...
    else
        -- undefined! let's define it!


        ffi.cdef[[
            struct in_addr {
                uint32_t s_addr;
            };
        ]]
    end

参考地址

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进