[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: any plan about luajit2 support 5.2!
- From: Mike Pall <mikelu-1011@...>
- Date: Wed, 17 Nov 2010 19:44:56 +0100
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:
ffi.cdef[[
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 = ffi.new("foo_t")
obj.b.y = 42 -- Nested accessors work fine.
obj.c = true -- Implicitly coerced to 1.
local obj2 = ffi.new(obj) -- 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 = ffi.new(color_t, 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
end
-- Shows automatic FP to int conversion:
local gray = ffi.new("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
end
-- And in the future ...
ffi.cdef[[
int mkdir(const char *pathname, unsigned int mode);
int rmdir(const char *pathname);
]]
ffi.C.mkdir("/tmp/test", 0x1ff) -- Yes, it's that simple!
ffi.C.rmdir("/tmp/test")
--Mike