lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I'm trying to add some kind of introspection to LuaJIT FFI, that will
allow to determine not only the type of a cdata object, but also list
it's fields. My goal is to recursively print/dump various complex data
structures in true Lua fashion (I'm trying it out on the ffmpeg
libraries using preprocessed headers). Currently I have this (warning,
bad code, it's my first attempt at modifying LuaJIT):

LJLIB_CF(ffi_fields)
{
  CTState *cts = ctype_cts(L);
  CTypeID id = ffi_checkctype(L, cts);
  CType *ct = lj_ctype_rawref(cts, id);
  if (ctype_isstruct(ct->info) && ct->size != CTSIZE_INVALID) {
    int i=0;
    lua_createtable(L,0,0);
    while (ct->sib) {
      ct = ctype_get(cts, ct->sib);
      setstrV(L, L->top++, gcrefp(ct->name, GCstr));
      lua_rawseti(L, -2, ++i);
    }
    return 1;
  } else {
    lj_err_argtype(L, 1, "struct type");
  }
  return 0;
}

When ffi.fields() is passed a struct type, or a name of such type, it
returns a table of strings, which are the names of fields in the
struct. However, it fails when I pass an instance/cdata object of such
type. When looking at ct->info, it is CT_PTR. How can I get to the
structure this pointer refers to? I've tried using ct =
ctype_child(cts, ct), but it fails later on setstrV() with assertion
error. I have a feeling I am abusing things I should not be touching
:).