Re: FFI, cURL and function callback

  • From: pingon begand <sbronfion@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Sun, 24 Mar 2013 17:17:57 +0100

2013/3/24 Szabó Antal <szabo.antal.92@xxxxxxxxx>

> 2013/3/24 pingon begand <sbronfion@xxxxxxxxx>:
> > The function callback is a memory sensitive task. Do you think something
> > like this will work as expected? :
> >
> > -- global variable where I store the data
> > data = ""
> > function cb(ptr, size, nmemb, stream)
> >         ffi.copy(data, ptr)
> > end
>
> You should add a third parameter to ffi.copy, the number of bytes to
> copy (see: http://luajit.org/ext_ffi_api.html ). Otherwise I think
> it's fine.
> Also, note that C to lua callbacks are much slower than the rest of
> the FFI, so avoid it if you want/need high performance.
>
>
Thanks a lot for all your help. I know it's rather slow but I am using this
only once. I don't know why, but it's not working for the moment, here is
an example :

#!/usr/bin/env luajit

local ffi = require "ffi"

ffi.cdef[[
void *curl_easy_init();
int curl_easy_setopt(void *curl, char option, ...);
int curl_easy_perform(void *curl);
void curl_easy_cleanup(void *curl);
]]

data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
function cb(ptr, size, nmemb, stream)
        ffi.copy(data, ptr, size*nmemb)
end

fptr = ffi.cast("size_t (*)(char *, size_t, size_t, void *)", cb)

local libcurl = ffi.load("libcurl.so")

local curl = libcurl.curl_easy_init()

local CURLOPT_URL = 10002
local CURLOPT_WRITEFUNCTION = 20011

if curl then
  libcurl.curl_easy_setopt(curl, CURLOPT_URL, "http://ipv4.icanhazip.com";)
  libcurl.curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fptr)
  res = libcurl.curl_easy_perform(curl)
  libcurl.curl_easy_cleanup(curl)
end

print(data)

Other related posts: