Re: FFI and endian conversion

  • From: Mike Pall <mike-1207@xxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Wed, 25 Jul 2012 12:45:27 +0200

Luke Gorrie wrote:
> I'm using LuaJIT's FFI to access things like ethernet frames as if they
> were C structures, and I'm wondering what the best way to take care of
> endian conversion is. Like: can I easily tell LuaJIT that I want automagic
> endian conversion on certain structure fields?

It's a low-level API, so the magic is limited. But it's easy
enough to add this functionality yourself:

  local ffi = require("ffi")
  local bit = require("bit")

  local function n32(x) return x end
  local n16 = n32
  if ffi.abi("le") then
    local shr = bit.rshift
    n32 = bit.bswap
    function n16(x) return shr(n32(x), 16) end

Then use n32(foo.field) or n16(foo.field) to access fields in
network byte order (aka ntohl or ntohs).

> } __attribute__ ((__packed__));

If you know you're on a host that allows unaligned access (e.g.
x86 and some ARMs), you can directly access the fields. Otherwise
you'll have to jump through some hoops: map it to a byte buffer
and piece the bytes together by hand.


Other related posts: