ffi.getmetatable

  • From: Ronan Collobert <ronan@xxxxxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Fri, 21 Nov 2014 15:23:45 -0800

Hi,

  At this time there is no (easy) way with luajit+ffi to get the metatable of a 
cdata/ctype. I understand the notion of metatable is ambiguous here, as the 
metatable given by the user through ffi.metatype() is not the actual one on the 
cdata (a global ffi-specific metatable that can be obtained by 
debug.getmetatable).

Reading the mailing list, I saw several people encountered the same issue (see 
for e.g. https://github.com/corsix/ffi-reflect and reflect.getmetatable).

Do you think it would be reasonable to have a ffi.getmetatable(ctype) function, 
which returns the original “metatable” given by user through ffi.metatype? 
(code in attachment) — If yes, I can work on the compiled version. I sincerely 
feel this is missing in the current ffi lib.

Thanks.
Ronan.


--- a/src/lib_ffi.c
+++ b/src/lib_ffi.c
@@ -558,6 +558,18 @@ LJLIB_CF(ffi_typeof)       LJLIB_REC(.)
   return 1;
 }
 
+LJLIB_CF(ffi_getmetatable)
+{
+  CTState *cts = ctype_cts(L);
+  CTypeID id = ffi_checkctype(L, cts, NULL);
+  cTValue *tv = lj_tab_getinth(cts->miscmap, -(int32_t)id);
+  if (tv && !tvisnil(tv)) {
+    copyTV(L, L->top-1, tv);
+    return 1;
+  }
+  return 0;
+}
+


Other related posts: