q66 / cffi-lua

A portable C FFI for Lua 5.1+
MIT License
176 stars 24 forks source link

help with libcurl #41

Closed lux5am closed 8 months ago

lux5am commented 11 months ago

I tried to use libcurl with cffi. It's fine in luajit. but with puc it give error libc: Fatal signal 11 (SIGSEGV), code 2 (SEGV_ACCERR), fault addr 0x7ac9a706e0 in tid 27717 (lua), pid 27717 (lua)

the problem is when doing curl_callback.

Also without this line in luajit also give strange incomplete result. maybe it's important to redefine the built-in typedefs which cffi fail to compile.

typedef int64_t time_t;
typedef unsigned int size_t;
local curl = require("libcurl-ffi")
-- local curl = require("luajit-curl")
local ffi = require"ffi" or require"cffi"

local ch = curl.curl_easy_init()

function curl_callback(callfunc)
  return ffi.cast("curl_callback", function (ptr, size, nmemb, stream)
    local bytes = size*nmemb
    local dst = ffi.new("char[?]", size*nmemb)
    ffi.copy(dst, ptr, size*nmemb)
    callfunc(ffi.string(dst, size*nmemb))
    return bytes
  end)
end
if (ch) then
    curl.curl_easy_setopt(ch, curl.CURLOPT_URL, "http://example.com")
    curl.curl_easy_setopt(ch, curl.CURLOPT_FOLLOWLOCATION, 1)

  local raw_body = {}
  local raw_header = {}

    local clb_write = curl_callback(function(s) table.insert(raw_body, s) end)
    local clb_header = curl_callback(function(s) table.insert(raw_header, s) end)

    curl.curl_easy_setopt(ch, curl.CURLOPT_WRITEFUNCTION, clb_write)
    curl.curl_easy_setopt(ch, curl.CURLOPT_HEADERFUNCTION, clb_header)

    local success, err = pcall(function()
        return curl.curl_easy_perform(ch)
    end)
    clb_write:free()
    clb_header:free()

    print(success, err)

    -- local result = curl.curl_easy_perform(ch)
    -- if (result ~= curl.CURLE_OK) then
        -- print("FAILURE:", ffi.string(curl.curl_easy_strerror(result)))
    -- end

    if #raw_header>0 then
      print(table.concat(raw_header))
    end
    print("bodylen:", #raw_body)

    curl.curl_easy_cleanup(ch)

    print("final>")
end

test_curl.lua.txt libcurl-ffi.lua.txt

lux5am commented 11 months ago

I found the problem. it's because the fallback returning ffi long instead of number like luajit. so I need to convert it first ffi.tonumber(size)