Re: opaque pointers and metatype

  • From: Richard Hundt <richardhundt@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Sun, 02 Mar 2014 19:39:17 +0100

On 3/2/14 6:38 PM, Cosmin Apreutesei wrote:
>> now you can just say:
>>
>> local handle = ffi.new('OpaqueStruct_t')
>> ffi.C.create(handle)
>> ffi.C.destroy(handle)
> By now, you mean lj 2.1 ? Cuz on 2.0 that gives me "size of C type is
> unknown or too large".
>
Sorry, typo (you probably want to ffi.new('OpaqueStruct_t[1]')).
However, what I was getting at is that you can do this:

```
ffi.cdef[[
typedef struct chunk_ chunk_t;
chunk_t* malloc(size_t);
void free(chunk_t*);
]]

ffi.metatype('chunk_t', {
   __index = {
      free = function(self)
         print("free: ", self)
         ffi.C.free(self)
      end
   }  
})

local chunk = ffi.C.malloc(42)
chunk:free()
```

In this sense the `void*` returned by `malloc()` is "opaque", but from
LuaJIT's perspective and you can give it a metatable.

The problem in your case is that `ffi.new` doesn't know the size, but I
think it only needs to know that it's a pointer. I haven't tried it, but
I guessed you can typedef that pointer to a struct without wrapping it,
as i've done with the `void*` returned by `malloc()`, and still have
your metatable.

I may, of course, have misunderstood your question. Happens :/


Other related posts: