luajit ffi implementing a chunk finalizer

I'm working on wraping libcurl in luajit ffi. My finalizer isn't getting called.

local ffi = require("ffi")

ffi.cdef [[
  typedef struct{} CURL;
  CURL * curl_easy_init();
  void curl_easy_cleanup(CURL *);
]]

local CURL_lib = ffi.load("../lib/libcurl.so")
local CURL_CTX

local CURL_CTX_mt = {
  __gc = function()  print "finalizing"; CURL_lib.curl_easy_cleanup(CURL_CTX); end
}

ffi.metatype("CURL", CURL_CTX_mt)

CURL_CTX = ffi.new("CURL[1]")
CURL_CTX = CURL_lib.curl_easy_init();
print "done"

What am I missing here ? :D

BTW CURL is defined as typedef void CURL; I'm sure the way I am trying to do it isn't clean enough. Any advice ?

eureka ! : self answer -- still interested in comments if there any glaring issues.

Answers


Compile time types in luajit must be structs (or unions I think) if you initialize your context type as a pointer, it is no longer a struct. So, there is a concept mismatch going on here. So, to fix things, add a void * to your struct, hang the metatype on the struct, and use the void * for the library context.

local ffi = require("ffi")

ffi.cdef [[
  typedef struct { void * ctx; } curl;
  curl * curl_easy_init();
  void curl_easy_cleanup(curl *);
]]

local curl_lib = ffi.load("../lib/libcurl.so")
local curl

local curl_mt = {
  __gc = function()  curl_lib.curl_easy_cleanup(curl.ctx); end
}

local curl_proto = ffi.metatype("curl", curl_mt)

curl = curl_proto(nil)
curl.ctx = curl_lib.curl_easy_init();

Or You can just register finalizer on returned pointer like this:

local ffi = require("ffi")

ffi.cdef [[
    typedef struct{} CURL;
    CURL * curl_easy_init();
    void curl_easy_cleanup(CURL *);
]]

local CURL_lib = ffi.load("../lib/libcurl.so")

local function curl_pointer_finalizer(pointer)
    print "finalizing"
    CURL_lib.curl_easy_cleanup(pointer)
end

local function curl_easy_init()
    return ffi.gc(CURL_lib.curl_easy_init(), curl_pointer_finalizer)
end

local CURL_CTX = curl_easy_init() -- wrapper func
print "done"

Need Your Help

Pass dynamic checkbox values to next JSP page

mysql jsp checkbox

I have aproblem. Here I am showing some bills from Invoice table in mysql. And for single bill I am keeping a checkbox. I want to pass selected checkbox values to next jsp page. Please help me to d...

CakePHP3 shows date with one hour difference

php cakephp

I am using CakePHP3 framework. In my MySQL database I have a datetime field. In this I have, for example this datetime: 2016-02-10 15:30:51. When I catch this field from CakePHP, I get the correct ...