分享

c

 quasiceo 2014-01-12

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.

asked Feb 22 '12 at 13:42
Hassan Syed
10.2k2583


 
if you discover an answer yourself, you should post it as an actual answer and accept it. –  Necrolis Feb 22 '12 at 14:11

 
aah I thought one had to wait for a timeout before a self-answer can be done. Thanks. Aah you cannot accept your own answer for 2 days. –  Hassan Syed Feb 22 '12 at 14:13
add comment

1 Answer

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();

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多