__len metamethod of pointer of struct

  • From: Peter Colberg <peter@xxxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Sat, 8 Sep 2012 14:16:47 -0400

Hi,

I would like to define a __len metamethod for an ffi struct type.
However, I do not have access to the struct itself, but to a pointer
to the struct:

    local ffi = require("ffi")
    ffi.cdef[[
    typedef struct MPI_Info_t *MPI_Info;
    int MPI_Info_get_nkeys(MPI_Info info, int *nkeys);
    ]]

The following test case reproduces the issue:

    -- struct_ptr_len.lua
    local ffi = require("ffi")
    local ctype = ffi.typeof("struct { int len; }")
    local ptype = ffi.typeof("$ *", ctype)

    local function len(self) return self.len end

    ffi.metatype(ctype, {__len = len, __tostring = len})

    local val = ctype(42)
    local ptr = ffi.cast(ptype, val)

    assert(tostring(val) == 42)
    assert(tostring(ptr) == 42)
    assert(#val == 42)
    assert(#ptr == 42)

The expression #ptr causes this error:

    luajit: struct_ptr_len.lua:15: attempt to get length of 'struct 95 *'
    stack traceback:
            struct_ptr_len.lua:15: in main chunk
            [C]: ?

Since __tostring works fine with a struct pointer, should __len work, too?

Thanks,
Peter

Other related posts: