Re: A way to associate a Lua value with a FFI pointer?

  • From: Mike Pall <mike-1404@xxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Wed, 9 Apr 2014 23:40:45 +0200

Alex wrote:
> A "void*" cdata object is simply a
> structure that holds a void* pointer. Thus, you have a reference to a cdata
> object that holds a pointer. LuaJIT is free to allocate different cdata
> 'containers' that point to the same pointer.

That's correct.

> Printing them prints the
> cdata's address, and not the address to which the cdata points.

Err no, printing a pointer shows the address it holds. But that's
just a convenience.

Anyway, this doesn't change what the documentation says about the
unsuitability of cdata objects as table keys:

  local ffi = require("ffi")
  local x = ffi.cast("void *", 0x12345678)
  local y = ffi.cast("void *", 0x12345678)
  print(x, y) -- Prints 0x12345678 twice.
  print(x == y) -- True, since pointers are compared by address.

  -- But these are still two different cdata objects, i.e. two table keys.
  for k,v in pairs({[x]=1, [y]=2}) do print(v) end -- Prints 1 and 2.

This weirdness is just a consequence of how Lua tables work and how
cdata objects had to be grafted onto the existing VM and language.
These problems wouldn't occur, if one were to design a language with
a tightly integrated FFI from scratch.

--Mike

Other related posts: