lua-users home
lua-l archive

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

Alex Bradbury wrote:
> Ah, it seems I've misunderstood the scope of your FFI. I was imagining
> something like Python ctypes or Lua alien, but JIT-aware and with
> better support for native data structures. I didn't realise that (if I
> understood you correctly) you've implemented a C parser as well. I'll
> be watching the git repository with great interest.

Ok, but don't hold your breath. It'll come in pieces and not
everything will work right away. Feedback is always welcome.

Here are some usage examples:

local ffi = require("ffi")

-- Type declarations:
  typedef struct foo {  /* With comments, too. */
    int8_t a;                             // C99 types are predefined.
    struct { char x; int y; char z; } b;  // Nested types are ok.
    bool c;                               // Supports special coercions.
    union { uint8_t v; uint16_t w; };     // And transparent structs/unions.
  } foo_t;
-- It takes a string, so you can construct arbitrary types at runtime!

-- Inspect type properties:
print(ffi.sizeof("struct foo"))    --> 20 -- Use the struct name.
print(ffi.sizeof("foo_t"))         --> 20 -- Or the typedef.
print(ffi.alignof("foo_t"))        --> 4
print(ffi.offsetof("foo_t", "c"))  --> 16
print(ffi.offsetof("foo_t", "w"))  --> 18

-- Create a cdata object (garbage collected, of course):
local obj ="foo_t")
obj.b.y = 42                       -- Nested accessors work fine.
obj.c = true                       -- Implicitly coerced to 1.

local obj2 =          -- Use another object as a template.
obj2.a = obj.b.y                   -- Automatic type conversion.
print(obj2.a)                      --> 42, obviously.

-- You can optionally resolve a complicated type to a handle:
local color_t = ffi.typeof("struct { uint8_t r,g,b,a; } [?]")

-- And later use it for creation:
local ctab =, 256) -- Note the parameterized type.
for i=0,255 do
  ctab[i].r, ctab[i].g, ctab[i].b, ctab[i].a = i, 255-i, 128, 255

-- Shows automatic FP to int conversion:
local gray ="uint8_t[?]", 256)
for i=0,255 do
  gray[i] = 0.3*ctab[i].r + 0.59*ctab[i].g + 0.11*ctab[i].b

-- And in the future ...
  int mkdir(const char *pathname, unsigned int mode);
  int rmdir(const char *pathname);

ffi.C.mkdir("/tmp/test", 0x1ff)    -- Yes, it's that simple!