首页 > 代码库 > 使用 luajit的ffi 调用libcurl

使用 luajit的ffi 调用libcurl

--以下是用Libcurl获取指定url文件version.txt的内容

 

local ffi = require "ffi"

ffi.cdef[[
void *curl_easy_init();
int curl_easy_setopt(void *curl, int option, ...);
int curl_easy_perform(void *curl);
void curl_easy_cleanup(void *curl);
char *curl_easy_strerror(int code);
int curl_easy_getinfo(void *curl, int info, ...);

typedef unsigned int (*WRITEFUNC)(void *ptr, unsigned int size, unsigned int nmemb, void *userdata);


--]]

local libcurl = ffi.load("libcurl")

 

local curl = libcurl.curl_easy_init()
if curl then

local version=""

--这是把LUA函数转换成c回调函数
local getVersionCode = ffi.cast("WRITEFUNC", function(ptr,size,nmemb,userdata)
version=version..ffi.string(ptr)
return size*nmemb
end)

libcurl.curl_easy_setopt(curl, CURLOPT_URL, RES_URL.."version.txt")
libcurl.curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0)
libcurl.curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, getVersionCode)
libcurl.curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1)
libcurl.curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1)
libcurl.curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, 5)

local res = libcurl.curl_easy_perform(curl)
if res ~= 0 then
print(ffi.string(libcurl.curl_easy_strerror(res)))
end
libcurl.curl_easy_cleanup(curl)
getVersionCode:free()

remoteVersion=tonumber(version)
end

使用 luajit的ffi 调用libcurl