From 425f67c7d6b33382d04ee1a9ade31b79150ec953 Mon Sep 17 00:00:00 2001
From: Mike Pall
-Please note: this doesn't comprise the final specification for the FFI -semantics, yet. Some semantics may need to be changed, based on your -feedback. Please report any problems you may -encounter or any improvements you'd like to see — thank you! -
@@ -813,6 +807,55 @@ possibly provide. +
+To facilitate some abstractions, the two functions +ffi.typeof and +ffi.cdef support +parameterized types in C declarations. Note: none of the other API +functions taking a cdecl allow this. +
++Any place you can write a typedef name, an +identifier or a number in a declaration, you can write +$ (the dollar sign) instead. These placeholders are replaced in +order of appearance with the arguments following the cdecl string: +
++-- Declare a struct with a parameterized field type and name: +ffi.cdef([[ +typedef struct { $ $; } foo_t; +]], type1, name1) + +-- Anonymous struct with dynamic names: +local bar_t = ffi.typeof("struct { int $, $; }", name1, name2) +-- Derived pointer type: +local bar_ptr_t = ffi.typeof("$ *", bar_t) + +-- Parameterized dimensions work even where a VLA won't work: +local matrix_t = ffi.typeof("uint8_t[$][$]", width, height) ++
+Caveat: this is not simple text substitution! A passed ctype or +cdata object is treated like the underlying type, a passed string is +considered an identifier and a number is considered a number. You must +not mix this up: e.g. passing "int" as a string doesn't work in +place of a type, you'd need to use ffi.typeof("int") instead. +
++The main use for parameterized types are libraries implementing abstract +data types +(» example), +similar to what can be achieved with C++ template metaprogramming. +Another use case are derived types of anonymous structs, which avoids +pollution of the global struct namespace. +
++Please note that parameterized types are a nice tool and indispensable +for certain use cases. But you'll want to use them sparingly in regular +code, e.g. when all types are actually fixed. +
+All explicitly (ffi.new(), ffi.cast() etc.) or @@ -1156,10 +1199,8 @@ value.
Other missing features: