文章目录
- C Language Support
- C Type Conversion Rules
- Conversions from C types to Lua objects
- 例子:访问结构体成员
- Conversions from Lua objects to C types
- Conversions between C types
- 例子:修改结构体成员
- Conversions for vararg C function arguments
- Initializers
- 例子:结构体初始化
- 例子:固定大小数组初始化
- 例子:变长数组初始化
- 例子:字节数组初始化
- 例子:嵌套结构体初始化
- Table Initializers
- 例子:使用 table 初始化数组或结构体
- Operations on cdata Objects
- Indexing a cdata object
- Calling a cdata object
- Arithmetic on cdata objects
- Comparisons of cdata objects
- cdata objects as table keys
- Garbage Collection of cdata Objects
- Callbacks
- Callback resource handling
- Callback performance
- C Library Namespaces
- No Hand-holding!
- Current Status
Given that the FFI library is designed to interface with C code and that declarations can be written in plain C syntax, it closely follows the C language semantics, wherever possible. Some minor concessions【轻微的让步】 are needed for smoother interoperation with Lua language semantics.
C Language Support
【忽略复数和向量类型】
The FFI library has a built-in C parser with a minimal memory footprint. It’s used by the ffi.* library functions to declare C types or external symbols.
Its only purpose is to parse C declarations, as found e.g. in C header files. Although it does evaluate constant expressions, it’s not a C compiler. The body of inline
C function definitions is simply ignored.
Also, this is not a validating C parser. It expects and accepts correctly formed C declarations, but it may choose to ignore bad declarations or show rather generic error messages. If in doubt, please check the input against your favorite C compiler.
The C parser complies to the C99 language standard plus the following extensions:
- The
'\e'
escape in character and string literals. - The C99/C++ boolean type, declared with the keywords
bool
or_Bool
. - Unnamed (‘transparent’)
struct
/union
fields inside astruct
/union
. - Incomplete
enum
declarations, handled like incompletestruct
declarations. - Unnamed
enum
fields inside astruct
/union
. This is similar to a scoped C++enum
, except that declared constants are visible in the global namespace, too. - Scoped
static const
declarations inside astruct
/union
(from C++). - Zero-length arrays (
[0]
), emptystruct
/union
, variable-length arrays (VLA,[?]
) and variable-length structs (VLS, with a trailing VLA). - C++ reference types (
int &x
). - Alternate GCC keywords with ‘
__
’, e.g.__const__
. - GCC
__attribute__
with the following attributes:aligned
,packed
,mode
,vector_size
,cdecl
,fastcall
,stdcall
,thiscall
. - The GCC
__extension__
keyword and the GCC__alignof__
operator. - GCC
__asm__("symname")
symbol name redirection for function declarations. - MSVC keywords for fixed-length types:
__int8
,__int16
,__int32
and__int64
. - MSVC
__cdecl
,__fastcall
,__stdcall
,__thiscall
,__ptr32
,__ptr64
,__declspec(align(n))
and#pragma pack
. - All other GCC/MSVC-specific attributes are ignored.
The following C types are predefined by the C parser (like a typedef
, except re-declarations will be ignored):
- Vararg handling:
va_list
,__builtin_va_list
,__gnuc_va_list
. - From
<stddef.h>
:ptrdiff_t
,size_t
,wchar_t
. - From
<stdint.h>
:int8_t
,int16_t
,int32_t
,int64_t
,uint8_t
,uint16_t
,uint32_t
,uint64_t
,intptr_t
,uintptr_t
. - From
<unistd.h>
(POSIX):ssize_t
.
You’re encouraged to use these types in preference to compiler-specific extensions or target-dependent standard types. E.g. char
differs in signedness and long
differs in size, depending on the target architecture and platform ABI.
The following C features are not supported:
- A declaration must always have a type specifier; it doesn’t default to an
int
type. - Old-style empty function declarations (K&R) are not allowed. All C functions must have a proper prototype declaration. A function declared without parameters (
int foo();
) is treated as a function taking zero arguments, like in C++. - The
long double
C type is parsed correctly, but there’s no support for the related conversions, accesses or arithmetic operations. - Wide character strings and character literals are not supported.
- See below for features that are currently not implemented.
C Type Conversion Rules
Conversions from C types to Lua objects
These conversion rules apply for read accesses to C types: indexing pointers, arrays or struct
/union
types; reading external variables or constant values; retrieving return values from C calls:
Input | Conversion | Output |
---|---|---|
int8_t , int16_t
|
→sign-ext int32_t → double
|
number |
uint8_t , uint16_t
|
→zero-ext int32_t → double
|
number |
int32_t , uint32_t
|
→ double
|
number |
int64_t , uint64_t
|
boxed value | 64 bit int cdata |
double , float
|
→ double
|
number |
bool |
0 → false , otherwise true
|
boolean |
enum |
boxed value | enum cdata |
Pointer | boxed value | pointer cdata |
Array | boxed reference | reference cdata |
struct /union
|
boxed reference | reference cdata |
Bitfields are treated like their underlying type.
Reference types are dereferenced before a conversion can take place — the conversion is applied to the C type pointed to by the reference.
例子:访问结构体成员
local ffi = require("ffi")
ffi.cdef [[
typedef enum {
RED = 1,
GREEN = 2,
BLUE = 3
} Colors;
typedef struct {
float x, y;
} point;
typedef struct {
int8_t a;
uint16_t b;
uint32_t c;
uint64_t d;
double e;
float f;
bool g;
Colors h;
int *i;
char j[100];
point k;
} t;
]]
local function print_type(v)
if type(v) ~= "cdata" then
print(type(v))
else
print(v)
end
end
local t = ffi.new("t")
print_type(t) -- cdata<struct 106>: 0x7fa50ecd6228
print_type(t.a) -- int8_t -> number
print_type(t.b) -- uint16_t -> number
print_type(t.c) -- uint32_t -> number
print_type(t.d) -- uint64_t -> 0ULL 【64 bit int cdata】
print_type(t.e) -- double -> number
print_type(t.f) -- float -> number
print_type(t.g) -- bool -> boolean
print_type(t.h) -- enum -> cdata<enum 97>: 0 【boxed value】
print_type(t.i) -- pointer -> cdata<int *>: NULL 【boxed value】
print_type(t.j) -- array -> cdata<char (&)[100]>: 0x7fa50ecd6258 【boxed reference】
print_type(t.k) -- struct -> cdata<struct 102 &>: 0x7fa50ecd62bc 【boxed reference】
会发生 C 类型到 Lua 类型的转换
Conversions from Lua objects to C types
These conversion rules apply for write accesses to C types: indexing pointers, arrays or struct
/union
types; initializing cdata objects; casts to C types; writing to external variables; passing arguments to C calls:
Input | Conversion | Output |
---|---|---|
number | → | double |
boolean |
false → 0, true → 1 |
bool |
nil |
NULL → |
(void *) |
lightuserdata | lightuserdata address → | (void *) |
userdata | userdata payload → | (void *) |
io.* file | get FILE * handle → | (void *) |
string | match against enum constant |
enum |
string | copy string data + zero-byte |
int8_t[] , uint8_t[]
|
string | string data → | const char[] |
function | create callback → | C function type |
table | table initializer | Array |
table | table initializer |
struct /union
|
cdata | cdata payload → | C type |
If the result type of this conversion doesn’t match the C type of the destination, the conversion rules between C types are applied.
Conversions between C types
These conversion rules are more or less the same as the standard C conversion rules. Some rules only apply to casts, or require pointer or type compatibility:
Input | Conversion | Output |
---|---|---|
Signed integer | →narrow or sign-extend | Integer |
Unsigned integer | →narrow or zero-extend | Integer |
Integer | →round |
double , float
|
double , float
|
→trunc int32_t →narrow |
(u)int8_t , (u)int16_t
|
double , float
|
→trunc |
(u)int32_t , (u)int64_t
|
double , float
|
→round |
float , double
|
Number | n == 0 → 0, otherwise 1 | bool |
bool |
false → 0, true → 1 |
Number |
struct /union
|
take base address (compat) | Pointer |
Array | take base address (compat) | Pointer |
Function | take function address | Function pointer |
Number | convert via uintptr_t (cast) |
Pointer |
Pointer | convert address (compat/cast) | Pointer |
Pointer | convert address (cast) | Integer |
Array | convert base address (cast) | Integer |
Array | copy (compat) | Array |
struct /union
|
copy (identical type) |
struct /union
|
Bitfields or enum
types are treated like their underlying type.
Conversions not listed above will raise an error. E.g. it’s not possible to convert a pointer to a complex number or vice versa.
例子:修改结构体成员
local ffi = require("ffi")
ffi.cdef [[
typedef enum {
RED = 1,
GREEN = 2,
BLUE = 3
} Colors;
typedef struct {
float x, y;
} point;
typedef struct {
int8_t a;
uint16_t b;
uint32_t c;
uint64_t d;
double e;
float f;
bool g;
Colors h;
int *i;
char j[100];
point k;
} t;
]]
local t = ffi.new("t")
t.a = 1 -- number -> double -> int8_t
t.b = 2 -- number -> double -> uint16_t
t.c = 3 -- number -> double -> uint16_t
t.d = 4 -- number -> double -> uint64_t
t.e = 5 -- number -> double
t.f = 6 -- number -> double -> float
t.g = 7 -- number -> double -> 1 【n == 0 → 0, otherwise 1】
t.h = "BLUE" -- string -> enmu 【match against `enum` constant】
local i = ffi.new("int [1]", 1)
t.i = i -- cdata -> int [1]【数组】 -> pointer 【take base address (compat)】
t.j = ffi.new("char [100]", "abc") -- cdata -> char [100]
t.k = ffi.new("point", 1, 2) -- cdata -> point
会发生 Lua 类型到 C 类型的转换。如果按照转换规则无法转换,则运行时会报错。
Conversions for vararg C function arguments
The following default conversion rules apply when passing Lua objects to the variable argument part of vararg C functions:
Input | Conversion | Output |
---|---|---|
number | → | double |
boolean |
false → 0, true → 1 |
bool |
nil |
NULL → |
(void *) |
userdata | userdata payload → | (void *) |
lightuserdata | lightuserdata address → | (void *) |
string | string data → | const char * |
float cdata |
→ | double |
Array cdata | take base address | Element pointer |
struct /union cdata |
take base address |
struct /union pointer |
Function cdata | take function address | Function pointer |
Any other cdata | no conversion | C type |
To pass a Lua object, other than a cdata object, as a specific type, you need to override the conversion rules: create a temporary cdata object with a constructor or a cast and initialize it with the value to pass:
Assuming x
is a Lua number, here’s how to pass it as an integer to a vararg function:
ffi.cdef[[
int printf(const char *fmt, ...);
]]
ffi.C.printf("integer value: %d\n", ffi.new("int", x))
If you don’t do this, the default Lua number → double
conversion rule applies. A vararg C function expecting an integer will see a garbled or uninitialized value.
Note: this is the only place where creating a boxed scalar number type is actually useful. Never use ffi.new("int")
, ffi.new("float")
etc. anywhere else!【只有在作为可变参数 C 函数的参数时才用得到这种写法!】
Ditto for ffi.cast()
. Explicitly boxing scalars does not improve performance or force int
or float
arithmetic! It just adds costly boxing, unboxing and conversions steps. And it may lead to surprise results, because cdata arithmetic on scalar numbers is always performed on 64 bit integers.
Initializers
Creating a cdata object with ffi.new() or the equivalent constructor syntax always initializes its contents, too. Different rules apply, depending on the number of optional initializers and the C types involved:
- If no initializers are given, the object is filled with zero bytes.
- Scalar types (numbers and pointers) accept a single initializer. The Lua object is converted to the scalar C type.
- Aggregate types (arrays and structs) accept either a single cdata initializer of the same type (copy constructor), a single table initializer, or a flat list of initializers.
例子:结构体初始化
local ffi = require("ffi")
ffi.cdef [[
typedef struct {
int a,b,c;
} t;
]]
local t1 = ffi.new("t", { 1 }) -- 1 0 0
local t2 = ffi.new("t", { 1, 2 }) -- 1 2 0
local t3 = ffi.new("t", 1) -- 1 0 0
local t4 = ffi.new("t", 1, 2) -- 1 2 0
local t5 = ffi.new("t", t4) -- 1 2 0
-- local t6 = ffi.new("t", 1, 2, 3, 4) -- 报错
local t7 = ffi.new("t", {1, 2, 3, 4}) -- 不会报错,忽略多余的元素
- The elements of an array are initialized, starting at index zero. If a single initializer is given for an array, it’s repeated for all remaining elements. This doesn’t happen if two or more initializers are given: all remaining uninitialized elements are filled with zero bytes.
例子:固定大小数组初始化
local a1 = ffi.new("int [3]", 1) -- 1 1 1
print_array(a1, 3)
local a2 = ffi.new("int [3]", 1, 2) -- 1 2 0
print_array(a2, 3)
local a3 = ffi.new("int [3]", {1}) -- 1 1 1
print_array(a3, 3)
local a4 = ffi.new("int [3]", {1, 2}) -- 1 2 0
print_array(a4, 3)
- Byte arrays may also be initialized with a Lua string. This copies the whole string plus a terminating zero-byte. The copy stops early only if the array has a known, fixed size.
例子:变长数组初始化
local a1 = ffi.new("int [?]", 3, 1) -- 1 1 1
local a2 = ffi.new("int [?]", 3, 1, 2) -- 1 2 0
local a3 = ffi.new("int [?]", 3, {1}) -- 1 ? ?
local a4 = ffi.new("int [?]", 3, {1, 2}) -- 1 2 ?
例子:字节数组初始化
local s = ffi.new("char [100]", "hello world!")
print(ffi.string(s)) -- hello world!
- The fields of a
struct
are initialized in the order of their declaration. Uninitialized fields are filled with zero bytes. - Only the first field of a
union
can be initialized with a flat initializer. - Elements or fields which are aggregates themselves are initialized with a single initializer, but this may be a table initializer or a compatible aggregate.
例子:嵌套结构体初始化
local ffi = require("ffi")
ffi.cdef [[
typedef struct {
float x, y;
} point;
typedef struct {
int a,b,c;
point d;
} t;
]]
local t1 = ffi.new("t", 1, 2, 3, {1, 2})
local t2 = ffi.new("t", 1, 2, 3, ffi.new("point", 1, 2))
local t3 = ffi.new("t", {a = 1, d = {1, 2}})
- Excess initializers cause an error.
Table Initializers
The following rules apply if a Lua table is used to initialize an Array or a struct
/union
:
- If the table index
[0]
is non-nil
, then the table is assumed to be zero-based. Otherwise it’s assumed to be one-based. - Array elements, starting at index zero, are initialized one-by-one with the consecutive table elements, starting at either index
[0]
or[1]
. This process stops at the firstnil
table element. - If exactly one array element was initialized, it’s repeated for all the remaining elements. Otherwise all remaining uninitialized elements are filled with zero bytes.
- The above logic only applies to arrays with a known fixed size. A VLA is only initialized with the element(s) given in the table. Depending on the use case, you may need to explicitly add a
NULL
or0
terminator to a VLA.
参考上面的数组初始化例子。
- A
struct
/union
can be initialized in the order of the declaration of its fields. Each field is initialized with consecutive table elements, starting at either index[0]
or[1]
. This process stops at the firstnil
table element. - Otherwise, if neither index
[0]
nor[1]
is present, astruct
/union
is initialized by looking up each field name (as a string key) in the table. Each non-nil
value is used to initialize the corresponding field.
参考上面的嵌套结构体初始化例子。
- Uninitialized fields of a
struct
are filled with zero bytes, except for the trailing VLA of a VLS. - Initialization of a
union
stops after one field has been initialized. If no field has been initialized, theunion
is filled with zero bytes. - Elements or fields which are aggregates themselves are initialized with a single initializer, but this may be a nested table initializer (or a compatible aggregate).
参考上面的嵌套结构体初始化例子。
- Excess initializers for an array cause an error. Excess initializers for a
struct
/union
are ignored. Unrelated table entries are ignored, too.
例子:使用 table 初始化数组或结构体
local ffi = require("ffi")
ffi.cdef[[
struct foo { int a, b; };
union bar { int i; double d; };
struct nested { int x; struct foo y; };
]]
ffi.new("int[3]", {}) --> 0, 0, 0
ffi.new("int[3]", {1}) --> 1, 1, 1
ffi.new("int[3]", {1,2}) --> 1, 2, 0
ffi.new("int[3]", {1,2,3}) --> 1, 2, 3
ffi.new("int[3]", {[0]=1}) --> 1, 1, 1
ffi.new("int[3]", {[0]=1,2}) --> 1, 2, 0
ffi.new("int[3]", {[0]=1,2,3}) --> 1, 2, 3
ffi.new("int[3]", {[0]=1,2,3,4}) --> error: too many initializers
ffi.new("struct foo", {}) --> a = 0, b = 0
ffi.new("struct foo", {1}) --> a = 1, b = 0
ffi.new("struct foo", {1,2}) --> a = 1, b = 2
ffi.new("struct foo", {[0]=1,2}) --> a = 1, b = 2
ffi.new("struct foo", {b=2}) --> a = 0, b = 2
ffi.new("struct foo", {a=1,b=2,c=3}) --> a = 1, b = 2 'c' is ignored
ffi.new("union bar", {}) --> i = 0, d = 0.0
ffi.new("union bar", {1}) --> i = 1, d = ?
ffi.new("union bar", {[0]=1,2}) --> i = 1, d = ? '2' is ignored
ffi.new("union bar", {d=2}) --> i = ?, d = 2.0
ffi.new("struct nested", {1,{2,3}}) --> x = 1, y.a = 2, y.b = 3
ffi.new("struct nested", {x=1,y={2,3}}) --> x = 1, y.a = 2, y.b = 3
Operations on cdata Objects
All standard Lua operators can be applied to cdata objects or a mix of a cdata object and another Lua object. The following list shows the predefined operations.
Reference types are dereferenced before performing each of the operations below — the operation is applied to the C type pointed to by the reference.
The predefined operations are always tried first before deferring to a metamethod or index table (if any) for the corresponding ctype (except for __new
). An error is raised if the metamethod lookup or index table lookup fails.
Indexing a cdata object
- Indexing a pointer/array: a cdata pointer/array can be indexed by a cdata number or a Lua number. The element address is computed as the base address plus the number value multiplied by the element size in bytes. A read access loads the element value and converts it to a Lua object. A write access converts a Lua object to the element type and stores the converted value to the element. An error is raised if the element size is undefined or a write access to a constant element is attempted.
-
Dereferencing a
struct
/union
field: a cdatastruct
/union
or a pointer to astruct
/union
can be dereferenced by a string key, giving the field name. The field address is computed as the base address plus the relative offset of the field. A read access loads the field value and converts it to a Lua object. A write access converts a Lua object to the field type and stores the converted value to the field. An error is raised if a write access to a constantstruct
/union
or a constant field is attempted. Scoped enum constants or static constants are treated like a constant field.
A ctype object can be indexed with a string key, too. The only predefined operation is reading scoped constants of struct
/union
types. All other accesses defer to the corresponding metamethods or index tables (if any).
Note: since there’s (deliberately) no address-of operator, a cdata object holding a value type is effectively immutable after initialization. The JIT compiler benefits from this fact when applying certain optimizations.
As a consequence, the elements of complex numbers and vectors are immutable. But the elements of an aggregate holding these types may be modified, of course. I.e. you cannot assign to foo.c.im
, but you can assign a (newly created) complex number to foo.c
.
The JIT compiler implements strict aliasing rules: accesses to different types do not alias, except for differences in signedness (this applies even to char
pointers, unlike C99). Type punning through unions is explicitly detected and allowed.
Calling a cdata object
-
Constructor: a ctype object can be called and used as a constructor. This is equivalent to
ffi.new(ct, ...)
, unless a__new
metamethod is defined. The__new
metamethod is called with the ctype object plus any other arguments passed to the constructor. Note that you have to useffi.new
inside the metamethod, since callingct(...)
would cause infinite recursion. -
C function call: a cdata function or cdata function pointer can be called. The passed arguments are converted to the C types of the parameters given by the function declaration. Arguments passed to the variable argument part of vararg C function use special conversion rules. This C function is called and the return value (if any) is converted to a Lua object.
On Windows/x86 systems,__stdcall
functions are automatically detected, and a function declared as__cdecl
(the default) is silently fixed up after the first call.
Arithmetic on cdata objects
- Pointer arithmetic: a cdata pointer/array and a cdata number or a Lua number can be added or subtracted. The number must be on the right-hand side for a subtraction. The result is a pointer of the same type with an address plus or minus the number value multiplied by the element size in bytes. An error is raised if the element size is undefined.
- Pointer difference: two compatible cdata pointers/arrays can be subtracted. The result is the difference between their addresses, divided by the element size in bytes. An error is raised if the element size is undefined or zero.
-
64 bit integer arithmetic: the standard arithmetic operators (
+ - * / % ^
and unary minus) can be applied to two cdata numbers, or a cdata number and a Lua number. If one of them is anuint64_t
, the other side is converted to anuint64_t
and an unsigned arithmetic operation is performed. Otherwise, both sides are converted to anint64_t
and a signed arithmetic operation is performed. The result is a boxed 64 bit cdata object.
If one of the operands is anenum
and the other operand is a string, the string is converted to the value of a matchingenum
constant before the above conversion.
These rules ensure that 64 bit integers are “sticky”. Any expression involving at least one 64 bit integer operand results in another one. The undefined cases for the division, modulo and power operators return2LL ^ 63
or2ULL ^ 63
.
You’ll have to explicitly convert a 64 bit integer to a Lua number (e.g. for regular floating-point calculations) withtonumber()
. But note this may incur a precision loss. -
64 bit bitwise operations: the rules for 64 bit arithmetic operators apply analogously.
Unlike the otherbit.*
operations,bit.tobit()
converts a cdata number viaint64_t
toint32_t
and returns a Lua number.
Forbit.band()
,bit.bor()
andbit.bxor()
, the conversion toint64_t
oruint64_t
applies to all arguments, if any argument is a cdata number.
For all other operations, only the first argument is used to determine the output type. This implies that a cdata number as a shift count for shifts and rotates is accepted, but that alone does not cause a cdata number output.
Comparisons of cdata objects
-
Pointer comparison: two compatible cdata pointers/arrays can be compared. The result is the same as an unsigned comparison of their addresses.
nil
is treated like aNULL
pointer, which is compatible with any other pointer type. -
64 bit integer comparison: two cdata numbers, or a cdata number and a Lua number can be compared with each other. If one of them is an
uint64_t
, the other side is converted to anuint64_t
and an unsigned comparison is performed. Otherwise, both sides are converted to anint64_t
and a signed comparison is performed.
If one of the operands is anenum
and the other operand is a string, the string is converted to the value of a matchingenum
constant before the above conversion. - Comparisons for equality/inequality never raise an error. Even incompatible pointers can be compared for equality by address. Any other incompatible comparison (also with non-cdata objects) treats the two sides as unequal.
cdata objects as table keys
Lua tables may be indexed by cdata objects, but this doesn’t provide any useful semantics — cdata objects are unsuitable as table keys! 【cdata 对象不适合作为 table 的 keys】
A cdata object is treated like any other garbage-collected object and is hashed and compared by its address for table indexing. Since there’s no interning for cdata value types, the same value may be boxed in different cdata objects with different addresses. Thus, t[1LL+1LL]
and t[2LL]
usually do not point to the same hash slot, and they certainly do not point to the same hash slot as t[2]
.
It would seriously drive up implementation complexity and slow down the common case, if one were to add extra handling for by-value hashing and comparisons to Lua tables. Given the ubiquity of their use inside the VM, this is not acceptable.
There are three viable alternatives, if you really need to use cdata objects as keys:
- If you can get by with the precision of Lua numbers (52 bits), then use
tonumber()
on a cdata number or combine multiple fields of a cdata aggregate to a Lua number. Then use the resulting Lua number as a key when indexing tables.
One obvious benefit:t[tonumber(2LL)]
does point to the same slot ast[2]
. - Otherwise, use either
tostring()
on 64 bit integers or complex numbers or combine multiple fields of a cdata aggregate to a Lua string (e.g. with ffi.string()). Then use the resulting Lua string as a key when indexing tables. - Create your own specialized hash table implementation using the C types provided by the FFI library, just like you would in C code. Ultimately, this may give much better performance than the other alternatives or what a generic by-value hash table could possibly provide.
Garbage Collection of cdata Objects
All explicitly (ffi.new()
, ffi.cast()
etc.) or implicitly (accessors) created cdata objects are garbage collected. You need to ensure to retain valid references to cdata objects somewhere on a Lua stack, an upvalue or in a Lua table while they are still in use. Once the last reference to a cdata object is gone, the garbage collector will automatically free the memory used by it (at the end of the next GC cycle).
Please note, that pointers themselves are cdata objects, however they are not followed by the garbage collector. So e.g. if you assign a cdata array to a pointer, you must keep the cdata object holding the array alive as long as the pointer is still in use:
ffi