aboutsummaryrefslogtreecommitdiff
path: root/doc
diff options
context:
space:
mode:
authorMike Pall <mike>2011-02-10 03:12:09 +0100
committerMike Pall <mike>2011-02-10 03:12:09 +0100
commita2f9f1f831c77b19433b9f8858b9c1db0e421800 (patch)
treef662ad1b9f27533e228d52a7ff417e4ac8bcc19d /doc
parenta7ab6b2dc920e76d0cebd577e77bf3a043e3867d (diff)
downloadluajit-a2f9f1f831c77b19433b9f8858b9c1db0e421800.tar.gz
luajit-a2f9f1f831c77b19433b9f8858b9c1db0e421800.tar.bz2
luajit-a2f9f1f831c77b19433b9f8858b9c1db0e421800.zip
FFI: Finish docs on FFI semantics. Phew.
Diffstat (limited to 'doc')
-rw-r--r--doc/ext_ffi_semantics.html555
1 files changed, 521 insertions, 34 deletions
diff --git a/doc/ext_ffi_semantics.html b/doc/ext_ffi_semantics.html
index f48c6406..b2b3af30 100644
--- a/doc/ext_ffi_semantics.html
+++ b/doc/ext_ffi_semantics.html
@@ -8,6 +8,12 @@
8<meta name="Language" content="en"> 8<meta name="Language" content="en">
9<link rel="stylesheet" type="text/css" href="bluequad.css" media="screen"> 9<link rel="stylesheet" type="text/css" href="bluequad.css" media="screen">
10<link rel="stylesheet" type="text/css" href="bluequad-print.css" media="print"> 10<link rel="stylesheet" type="text/css" href="bluequad-print.css" media="print">
11<style type="text/css">
12table.convtable { line-height: 1.2; }
13tr.convhead td { font-weight: bold; }
14td.convin { width: 11em; }
15td.convop { font-style: italic; width: 16em; }
16</style>
11</head> 17</head>
12<body> 18<body>
13<div id="site"> 19<div id="site">
@@ -63,10 +69,25 @@ and its interaction with both Lua and C&nbsp;code.
63<p> 69<p>
64Given that the FFI library is designed to interface with C&nbsp;code 70Given that the FFI library is designed to interface with C&nbsp;code
65and that declarations can be written in plain C&nbsp;syntax, it 71and that declarations can be written in plain C&nbsp;syntax, it
66closely follows the C&nbsp;language semantics wherever possible. Some 72closely follows the C&nbsp;language semantics, wherever possible. Some
67concessions are needed for smoother interoperation with Lua language 73minor concessions are needed for smoother interoperation with Lua
68semantics. But it should be straightforward to write applications 74language semantics.
69using the LuaJIT FFI for developers with a C or C++ background. 75</p>
76<p>
77Please don't be overwhelmed by the contents of this page &mdash; this
78is a reference and you may need to consult it, if in doubt. It doesn't
79hurt to skim this page, but most of the semantics "just work" as you'd
80expect them to work. It should be straightforward to write
81applications using the LuaJIT FFI for developers with a C or C++
82background.
83</p>
84<p class="indent" style="color: #c00000;">
85Please note: this is the first public release of the FFI library. This
86does not comprise the final specification for the FFI semantics, yet.
87Some of the semantics may need to be changed, based on feedback from
88developers. Please <a href="contact.html">report</a> any problems
89you've encountered or any improvements you'd like to see &mdash; thank
90you!
70</p> 91</p>
71 92
72<h2 id="clang">C Language Support</h2> 93<h2 id="clang">C Language Support</h2>
@@ -93,12 +114,8 @@ the following extensions:
93</p> 114</p>
94<ul> 115<ul>
95 116
96<li>C++-style comments (<tt>//</tt>).</li>
97
98<li>The <tt>'\e'</tt> escape in character and string literals.</li> 117<li>The <tt>'\e'</tt> escape in character and string literals.</li>
99 118
100<li>The <tt>long long</tt> 64&nbsp;bit integer type.</tt>
101
102<li>The C99/C++ boolean type, declared with the keywords <tt>bool</tt> 119<li>The C99/C++ boolean type, declared with the keywords <tt>bool</tt>
103or <tt>_Bool</tt>.</li> 120or <tt>_Bool</tt>.</li>
104 121
@@ -122,14 +139,16 @@ inside a <tt>struct</tt>/<tt>union</tt>.</li>
122<tt>enum</tt>, except that declared constants are visible in the 139<tt>enum</tt>, except that declared constants are visible in the
123global namespace, too.</li> 140global namespace, too.</li>
124 141
125<li>C++-style scoped <tt>static&nbsp;const</tt> declarations inside a 142<li>Scoped <tt>static&nbsp;const</tt> declarations inside a
126<tt>struct</tt>/<tt>union</tt>.</li> 143<tt>struct</tt>/<tt>union</tt> (from C++).</li>
127 144
128<li>Zero-length arrays (<tt>[0]</tt>), empty 145<li>Zero-length arrays (<tt>[0]</tt>), empty
129<tt>struct</tt>/<tt>union</tt>, variable-length arrays (VLA, 146<tt>struct</tt>/<tt>union</tt>, variable-length arrays (VLA,
130<tt>[?]</tt>) and variable-length structs (VLS, with a trailing 147<tt>[?]</tt>) and variable-length structs (VLS, with a trailing
131VLA).</li> 148VLA).</li>
132 149
150<li>C++ reference types (<tt>int&nbsp;&amp;x</tt>).</li>
151
133<li>Alternate GCC keywords with '<tt>__</tt>', e.g. 152<li>Alternate GCC keywords with '<tt>__</tt>', e.g.
134<tt>__const__</tt>.</li> 153<tt>__const__</tt>.</li>
135 154
@@ -142,7 +161,7 @@ VLA).</li>
142<tt>__alignof__</tt> operator.</li> 161<tt>__alignof__</tt> operator.</li>
143 162
144<li>GCC <tt>__asm__("symname")</tt> symbol name redirection for 163<li>GCC <tt>__asm__("symname")</tt> symbol name redirection for
145function declarations.</tt> 164function declarations.</li>
146 165
147<li>MSVC keywords for fixed-length types: <tt>__int8</tt>, 166<li>MSVC keywords for fixed-length types: <tt>__int8</tt>,
148<tt>__int16</tt>, <tt>__int32</tt> and <tt>__int64</tt>.</li> 167<tt>__int16</tt>, <tt>__int32</tt> and <tt>__int64</tt>.</li>
@@ -204,18 +223,234 @@ not implemented.</li>
204</ul> 223</ul>
205 224
206<h2 id="convert">C Type Conversion Rules</h2> 225<h2 id="convert">C Type Conversion Rules</h2>
226
227<h3 id="convert_tolua">Conversions from C&nbsp;types to Lua objects</h3>
228<p>
229These conversion rules apply for <em>read accesses</em> to
230C&nbsp;types: indexing pointers, arrays or
231<tt>struct</tt>/<tt>union</tt> types; reading external variables or
232constant values; retrieving return values from C&nbsp;calls:
233</p>
234<table class="convtable">
235<tr class="convhead">
236<td class="convin">Input</td>
237<td class="convop">Conversion</td>
238<td class="convout">Output</td>
239</tr>
240<tr class="odd separate">
241<td class="convin"><tt>int8_t</tt>, <tt>int16_t</tt></td><td class="convop">&rarr;<sup>sign-ext</sup> <tt>int32_t</tt> &rarr; <tt>double</tt></td><td class="convout">number</td></tr>
242<tr class="even">
243<td class="convin"><tt>uint8_t</tt>, <tt>uint16_t</tt></td><td class="convop">&rarr;<sup>zero-ext</sup> <tt>int32_t</tt> &rarr; <tt>double</tt></td><td class="convout">number</td></tr>
244<tr class="odd">
245<td class="convin"><tt>int32_t</tt>, <tt>uint32_t</tt></td><td class="convop">&rarr; <tt>double</tt></td><td class="convout">number</td></tr>
246<tr class="even">
247<td class="convin"><tt>int64_t</tt>, <tt>uint64_t</tt></td><td class="convop">boxed value</td><td class="convout">64 bit int cdata</td></tr>
248<tr class="odd separate">
249<td class="convin"><tt>double</tt>, <tt>float</tt></td><td class="convop">&rarr; <tt>double</tt></td><td class="convout">number</td></tr>
250<tr class="even separate">
251<td class="convin"><tt>bool</tt></td><td class="convop">0 &rarr; <tt>true</tt>, otherwise <tt>false</tt></td><td class="convout">boolean</td></tr>
252<tr class="odd separate">
253<td class="convin">Complex number</td><td class="convop">boxed value</td><td class="convout">complex cdata</td></tr>
254<tr class="even">
255<td class="convin">Vector</td><td class="convop">boxed value</td><td class="convout">vector cdata</td></tr>
256<tr class="odd">
257<td class="convin">Pointer</td><td class="convop">boxed value</td><td class="convout">pointer cdata</td></tr>
258<tr class="even separate">
259<td class="convin">Array</td><td class="convop">boxed reference</td><td class="convout">reference cdata</td></tr>
260<tr class="odd">
261<td class="convin"><tt>struct</tt>/<tt>union</tt></td><td class="convop">boxed reference</td><td class="convout">reference cdata</td></tr>
262</table>
263<p>
264Bitfields or <tt>enum</tt> types are treated like their underlying
265type.
266</p>
267<p>
268Reference types are dereferenced <em>before</em> a conversion can take
269place &mdash; the conversion is applied to the C&nbsp;type pointed to
270by the reference.
271</p>
272
273<h3 id="convert_fromlua">Conversions from Lua objects to C&nbsp;types</h3>
274<p>
275These conversion rules apply for <em>write accesses</em> to
276C&nbsp;types: indexing pointers, arrays or
277<tt>struct</tt>/<tt>union</tt> types; initializing cdata objects;
278casts to C&nbsp;types; writing to external variables; passing
279arguments to C&nbsp;calls:
280</p>
281<table class="convtable">
282<tr class="convhead">
283<td class="convin">Input</td>
284<td class="convop">Conversion</td>
285<td class="convout">Output</td>
286</tr>
287<tr class="odd separate">
288<td class="convin">number</td><td class="convop">&rarr;</td><td class="convout"><tt>double</tt></td></tr>
289<tr class="even">
290<td class="convin">boolean</td><td class="convop"><tt>false</tt> &rarr; 0, <tt>true</tt> &rarr; 1</td><td class="convout"><tt>bool</tt></td></tr>
291<tr class="odd separate">
292<td class="convin">nil</td><td class="convop"><tt>NULL</tt> &rarr;</td><td class="convout"><tt>(void *)</tt></td></tr>
293<tr class="even">
294<td class="convin">userdata</td><td class="convop">userdata payload &rarr;</td><td class="convout"><tt>(void *)</tt></td></tr>
295<tr class="odd">
296<td class="convin">lightuserdata</td><td class="convop">lightuserdata address &rarr;</td><td class="convout"><tt>(void *)</tt></td></tr>
297<tr class="even separate">
298<td class="convin">string</td><td class="convop">match against <tt>enum</tt> constant</td><td class="convout"><tt>enum</tt></td></tr>
299<tr class="odd">
300<td class="convin">string</td><td class="convop">copy string data + zero-byte</td><td class="convout"><tt>int8_t[]</tt>, <tt>uint8_t[]</tt></td></tr>
301<tr class="even">
302<td class="convin">string</td><td class="convop">string data &rarr;</td><td class="convout"><tt>const char[]</tt></td></tr>
303<tr class="odd separate">
304<td class="convin">table</td><td class="convop"><a href="#init_table">table initializer</a></td><td class="convout">Array</td></tr>
305<tr class="even">
306<td class="convin">table</td><td class="convop"><a href="#init_table">table initializer</a></td><td class="convout"><tt>struct</tt>/<tt>union</tt></td></tr>
307<tr class="odd separate">
308<td class="convin">cdata</td><td class="convop">cdata payload &rarr;</td><td class="convout">C type</td></tr>
309</table>
310<p>
311If the result type of this conversion doesn't match the
312C&nbsp;type of the destination, the
313<a href="#convert_between">conversion rules between C&nbsp;types</a>
314are applied.
315</p>
316<p>
317Reference types are immutable after initialization ("no reseating of
318references"). For initialization purposes or when passing values to
319reference parameters, they are treated like pointers. Note that unlike
320in C++, there's no way to implement automatic reference generation of
321variables under the Lua language semantics. If you want to call a
322function with a reference parameter, you need to explicitly pass a
323one-element array.
324</p>
325
326<h3 id="convert_between">Conversions between C&nbsp;types</h3>
327<p>
328These conversion rules are more or less the same as the standard
329C&nbsp;conversion rules. Some rules only apply to casts, or require
330pointer or type compatibility:
331</p>
332<table class="convtable">
333<tr class="convhead">
334<td class="convin">Input</td>
335<td class="convop">Conversion</td>
336<td class="convout">Output</td>
337</tr>
338<tr class="odd separate">
339<td class="convin">Signed integer</td><td class="convop">&rarr;<sup>narrow or sign-extend</sup></td><td class="convout">Integer</td></tr>
340<tr class="even">
341<td class="convin">Unsigned integer</td><td class="convop">&rarr;<sup>narrow or zero-extend</sup></td><td class="convout">Integer</td></tr>
342<tr class="odd">
343<td class="convin">Integer</td><td class="convop">&rarr;<sup>round</sup></td><td class="convout"><tt>double</tt>, <tt>float</tt></td></tr>
344<tr class="even">
345<td class="convin"><tt>double</tt>, <tt>float</tt></td><td class="convop">&rarr;<sup>trunc</sup> <tt>int32_t</tt> &rarr;<sup>narrow</sup></td><td class="convout"><tt>(u)int8_t</tt>, <tt>(u)int16_t</tt></td></tr>
346<tr class="odd">
347<td class="convin"><tt>double</tt>, <tt>float</tt></td><td class="convop">&rarr;<sup>trunc</sup></td><td class="convout"><tt>(u)int32_t</tt>, <tt>(u)int64_t</tt></td></tr>
348<tr class="even">
349<td class="convin"><tt>double</tt>, <tt>float</tt></td><td class="convop">&rarr;<sup>round</sup></td><td class="convout"><tt>float</tt>, <tt>double</tt></td></tr>
350<tr class="odd separate">
351<td class="convin">Number</td><td class="convop">n == 0 &rarr; 0, otherwise 1</td><td class="convout"><tt>bool</tt></td></tr>
352<tr class="even">
353<td class="convin"><tt>bool</tt></td><td class="convop"><tt>false</tt> &rarr; 0, <tt>true</tt> &rarr; 1</td><td class="convout">Number</td></tr>
354<tr class="odd separate">
355<td class="convin">Complex number</td><td class="convop">convert real part</td><td class="convout">Number</td></tr>
356<tr class="even">
357<td class="convin">Number</td><td class="convop">convert real part, imag = 0</td><td class="convout">Complex number</td></tr>
358<tr class="odd">
359<td class="convin">Complex number</td><td class="convop">convert real and imag part</td><td class="convout">Complex number</td></tr>
360<tr class="even separate">
361<td class="convin">Number</td><td class="convop">convert scalar and replicate</td><td class="convout">Vector</td></tr>
362<tr class="odd">
363<td class="convin">Vector</td><td class="convop">copy (same size)</td><td class="convout">Vector</td></tr>
364<tr class="even separate">
365<td class="convin"><tt>struct</tt>/<tt>union</tt></td><td class="convop">take base address (compat)</td><td class="convout">Pointer</td></tr>
366<tr class="odd">
367<td class="convin">Array</td><td class="convop">take base address (compat)</td><td class="convout">Pointer</td></tr>
368<tr class="even">
369<td class="convin">Function</td><td class="convop">take function address</td><td class="convout">Function pointer</td></tr>
370<tr class="odd separate">
371<td class="convin">Number</td><td class="convop">convert via <tt>uintptr_t</tt> (cast)</td><td class="convout">Pointer</td></tr>
372<tr class="even">
373<td class="convin">Pointer</td><td class="convop">convert address (compat/cast)</td><td class="convout">Pointer</td></tr>
374<tr class="odd">
375<td class="convin">Pointer</td><td class="convop">convert address (cast)</td><td class="convout">Integer</td></tr>
376<tr class="even">
377<td class="convin">Array</td><td class="convop">convert base address (cast)</td><td class="convout">Integer</td></tr>
378<tr class="odd separate">
379<td class="convin">Array</td><td class="convop">copy (compat)</td><td class="convout">Array</td></tr>
380<tr class="even">
381<td class="convin"><tt>struct</tt>/<tt>union</tt></td><td class="convop">copy (identical type)</td><td class="convout"><tt>struct</tt>/<tt>union</tt></td></tr>
382</table>
383<p>
384Bitfields or <tt>enum</tt> types are treated like their underlying
385type.
386</p>
387<p>
388Conversions not listed above will raise an error. E.g. it's not
389possible to convert a pointer to a complex number or vice versa.
390</p>
391
392<h3 id="convert_vararg">Conversions for vararg C&nbsp;function arguments</h3>
393<p>
394The following default conversion rules apply when passing Lua objects
395to the variable argument part of vararg C&nbsp;functions:
396</p>
397<table class="convtable">
398<tr class="convhead">
399<td class="convin">Input</td>
400<td class="convop">Conversion</td>
401<td class="convout">Output</td>
402</tr>
403<tr class="odd separate">
404<td class="convin">number</td><td class="convop">&rarr;</td><td class="convout"><tt>double</tt></td></tr>
405<tr class="even">
406<td class="convin">boolean</td><td class="convop"><tt>false</tt> &rarr; 0, <tt>true</tt> &rarr; 1</td><td class="convout"><tt>bool</tt></td></tr>
407<tr class="odd separate">
408<td class="convin">nil</td><td class="convop"><tt>NULL</tt> &rarr;</td><td class="convout"><tt>(void *)</tt></td></tr>
409<tr class="even">
410<td class="convin">userdata</td><td class="convop">userdata payload &rarr;</td><td class="convout"><tt>(void *)</tt></td></tr>
411<tr class="odd">
412<td class="convin">lightuserdata</td><td class="convop">lightuserdata address &rarr;</td><td class="convout"><tt>(void *)</tt></td></tr>
413<tr class="even separate">
414<td class="convin">string</td><td class="convop">string data &rarr;</td><td class="convout"><tt>const char *</tt></td></tr>
415<tr class="odd separate">
416<td class="convin"><tt>float</tt> cdata</td><td class="convop">&rarr;</td><td class="convout"><tt>double</tt></td></tr>
417<tr class="even">
418<td class="convin">Array cdata</td><td class="convop">take base address</td><td class="convout">Element pointer</td></tr>
419<tr class="odd">
420<td class="convin"><tt>struct</tt>/<tt>union</tt> cdata</td><td class="convop">take base address</td><td class="convout"><tt>struct</tt>/<tt>union</tt> pointer</td></tr>
421<tr class="even">
422<td class="convin">Function cdata</td><td class="convop">take function address</td><td class="convout">Function pointer</td></tr>
423<tr class="odd">
424<td class="convin">Any other cdata</td><td class="convop">no conversion</td><td class="convout">C type</td></tr>
425</table>
426<p>
427To pass a Lua object, other than a cdata object, as a specific type,
428you need to override the conversion rules: create a temporary cdata
429object with a constructor or a cast and initialize it with the value
430to pass:
431</p>
432<p>
433Assuming <tt>x</tt> is a Lua number, here's how to pass it as an
434integer to a vararg function:
435</p>
436<pre class="code">
437ffi.cdef[[
438int printf(const char *fmt, ...);
439]]
440ffi.C.printf("integer value: %d\n", ffi.new("int", x))
441</pre>
207<p> 442<p>
208TODO 443If you don't do this, the default Lua number &rarr; <tt>double</tt>
444conversion rule applies. A vararg C&nbsp;function expecting an integer
445will see a garbled or uninitialized value.
209</p> 446</p>
210<h3 id="convert_tolua">Conversions from C&nbsp;types to Lua objects</h2>
211<h3 id="convert_fromlua">Conversions from Lua objects to C&nbsp;types</h2>
212<h3 id="convert_between">Conversions between C&nbsp;types</h2>
213 447
214<h2 id="init">Initializers</h2> 448<h2 id="init">Initializers</h2>
215<p> 449<p>
216Creating a cdata object with <a href="ffi_ext_api.html#ffi_new">ffi.new()</a> 450Creating a cdata object with
217or the equivalent constructor syntax always initializes its contents, 451<a href="ext_ffi_api.html#ffi_new"><tt>ffi.new()</tt></a> or the
218too. Different rules apply, depending on the number of optional 452equivalent constructor syntax always initializes its contents, too.
453Different rules apply, depending on the number of optional
219initializers and the C&nbsp;types involved: 454initializers and the C&nbsp;types involved:
220</p> 455</p>
221<ul> 456<ul>
@@ -230,8 +465,8 @@ when a single initializer is given. Otherwise they are treated like
230regular arrays.</li> 465regular arrays.</li>
231 466
232<li>Aggregate types (arrays and structs) accept either a single 467<li>Aggregate types (arrays and structs) accept either a single
233compound initializer (Lua table or string) or a flat list of 468<a href="#init_table">table initializer</a> or a flat list of initializers.
234initializers.</li> 469Byte arrays can be initialized with a Lua string, too.</li>
235 470
236<li>The elements of an array are initialized, starting at index zero. 471<li>The elements of an array are initialized, starting at index zero.
237If a single initializer is given for an array, it's repeated for all 472If a single initializer is given for an array, it's repeated for all
@@ -247,15 +482,272 @@ bytes.</li>
247flat initializer.</li> 482flat initializer.</li>
248 483
249<li>Elements or fields which are aggregates themselves are initialized 484<li>Elements or fields which are aggregates themselves are initialized
250with a <em>single</em> initializer, but this may be a compound 485with a <em>single</em> initializer, but this may be a table
251initializer or a compatible aggregate, of course.</li> 486initializer or a compatible aggregate.</li>
487
488<li>Excess initializers cause an error.</li>
252 489
253</ul> 490</ul>
254 491
255<h2 id="ops">Operations on cdata Objects</h2> 492<h2 id="init_table">Table Initializers</h2>
256<p> 493<p>
257TODO 494The following rules apply if a Lua table is used to initialize an
495Array or a <tt>struct</tt>/<tt>union</tt>:
258</p> 496</p>
497<ul>
498
499<li>If the table index <tt>[0]</tt> is non-<tt>nil</tt>, then the
500table is assumed to be zero-based. Otherwise it's assumed to be
501one-based.</li>
502
503<li>Array elements, starting at index zero, are initialized one-by-one
504with the consecutive table elements, starting at either index
505<tt>[0]</tt> or <tt>[1]</tt>. This process stops at the first
506<tt>nil</tt> table element.</li>
507
508<li>If exactly one array element was initialized, it's repeated for
509all the remaining elements. Otherwise all remaining uninitialized
510elements are filled with zero bytes.</li>
511
512<li>If the table has a non-empty hash part, a
513<tt>struct</tt>/<tt>union</tt> is initialized by looking up each field
514name (as a string key) in the table. Each non-<tt>nil</tt> value is
515used to initialize the corresponding field.</li>
516
517<li>Otherwise a <tt>struct</tt>/<tt>union</tt> is initialized in the
518order of the declaration of its fields. Each field is initialized with
519the consecutive table elements, starting at either index <tt>[0]</tt>
520or <tt>[1]</tt>. This process stops at the first <tt>nil</tt> table
521element.</li>
522
523<li>Uninitialized fields of a <tt>struct</tt> are filled with zero
524bytes.</li>
525
526<li>Initialization of a <tt>union</tt> stops after one field has been
527initialized. If no field has been initialized, the <tt>union</tt> is
528filled with zero bytes.</li>
529
530<li>Elements or fields which are aggregates themselves are initialized
531with a <em>single</em> initializer, but this may be a nested table
532initializer (or a compatible aggregate).</li>
533
534<li>Excess initializers for an array cause an error. Excess
535initializers for a <tt>struct</tt>/<tt>union</tt> are ignored.
536Unrelated table entries are ignored, too.</li>
537
538</ul>
539<p>
540Example:
541</p>
542<pre class="code">
543local ffi = require("ffi")
544
545ffi.cdef[[
546struct foo { int a, b; };
547union bar { int i; double d; };
548struct nested { int x; struct foo y; };
549]]
550
551ffi.new("int[3]", {}) --> 0, 0, 0
552ffi.new("int[3]", {1}) --> 1, 1, 1
553ffi.new("int[3]", {1,2}) --> 1, 2, 0
554ffi.new("int[3]", {1,2,3}) --> 1, 2, 3
555ffi.new("int[3]", {[0]=1}) --> 1, 1, 1
556ffi.new("int[3]", {[0]=1,2}) --> 1, 2, 0
557ffi.new("int[3]", {[0]=1,2,3}) --> 1, 2, 3
558ffi.new("int[3]", {[0]=1,2,3,4}) --> error: too many initializers
559
560ffi.new("struct foo", {}) --> a = 0, b = 0
561ffi.new("struct foo", {1}) --> a = 1, b = 0
562ffi.new("struct foo", {1,2}) --> a = 1, b = 2
563ffi.new("struct foo", {[0]=1,2}) --> a = 1, b = 2
564ffi.new("struct foo", {b=2}) --> a = 0, b = 2
565ffi.new("struct foo", {a=1,b=2,c=3}) --> a = 1, b = 2 'c' is ignored
566
567ffi.new("union bar", {}) --> i = 0, d = 0.0
568ffi.new("union bar", {1}) --> i = 1, d = ?
569ffi.new("union bar", {[0]=1,2}) --> i = 1, d = ? '2' is ignored
570ffi.new("union bar", {d=2}) --> i = ?, d = 2.0
571
572ffi.new("struct nested", {1,{2,3}}) --> x = 1, y.a = 2, y.b = 3
573ffi.new("struct nested", {x=1,y={2,3}}) --> x = 1, y.a = 2, y.b = 3
574</pre>
575
576<h2 id="cdata_ops">Operations on cdata Objects</h2>
577<p>
578All of the standard Lua operators can be applied to cdata objects or a
579mix of a cdata object and another Lua object. The following list shows
580the valid combinations. All other combinations currently raise an
581error.
582</p>
583<p>
584Reference types are dereferenced <em>before</em> performing each of
585the operations below &mdash; the operation is applied to the
586C&nbsp;type pointed to by the reference.
587</p>
588
589<h3 id="cdata_array">Indexing a cdata object</h3>
590<ul>
591
592<li><b>Indexing a pointer/array</b>: a cdata pointer/array can be
593indexed by a cdata number or a Lua number. The element address is
594computed as the base address plus the number value multiplied by the
595element size in bytes. A read access loads the element value and
596<a href="#convert_tolua">converts it to a Lua object</a>. A write
597access <a href="#convert_fromlua">converts a Lua object to the element
598type</a> and stores the converted value to the element. An error is
599raised if the element size is undefined or a write access to a
600constant element is attempted.</li>
601
602<li><b>Dereferencing a <tt>struct</tt>/<tt>union</tt> field</b>: a
603cdata <tt>struct</tt>/<tt>union</tt> or a pointer to a
604<tt>struct</tt>/<tt>union</tt> can be dereferenced by a string key,
605giving the field name. The field address is computed as the base
606address plus the relative offset of the field. A read access loads the
607field value and <a href="#convert_tolua">converts it to a Lua
608object</a>. A write access <a href="#convert_fromlua">converts a Lua
609object to the field type</a> and stores the converted value to the
610field. An error is raised if a write access to a constant
611<tt>struct</tt>/<tt>union</tt> or a constant field is attempted.</li>
612
613<li><b>Indexing a complex number</b>: a complex number can be indexed
614either by a cdata number or a Lua number with the values 0 or 1, or by
615the strings <tt>"re"</tt> or <tt>"im"</tt>. A read access loads the
616real part (<tt>[0]</tt>, <tt>.re</tt>) or the imaginary part
617(<tt>[1]</tt>, <tt>.im</tt>) part of a complex number and
618<a href="#convert_tolua">converts it to a Lua number</a>. The
619sub-parts of a complex number are immutable &mdash; assigning to an
620index of a complex number raises an error. Accessing out-of-bound
621indexes returns unspecified results, but is guaranteed not to trigger
622memory access violations.</li>
623
624<li><b>Indexing a vector</b>: a vector is treated like an array for
625indexing purposes, except the vector elements are immutable &mdash;
626assigning to an index of a vector raises an error.</li>
627
628</ul>
629<p>
630Note: since there's (deliberately) no address-of operator, a cdata
631object holding a value type is effectively immutable after
632initialization. The JIT compiler benefits from this fact when applying
633certain optimizations.
634</p>
635<p>
636As a consequence of this, the <em>elements</em> of complex numbers and
637vectors are immutable. But the elements of an aggregate holding these
638types <em>may</em> be modified of course. I.e. you cannot assign to
639<tt>foo.c.im</tt>, but you can assign a (newly created) complex number
640to <tt>foo.c</tt>.
641</p>
642
643<h3 id="cdata_call">Calling a cdata object</h3>
644<ul>
645
646<li><b>Constructor</b>: a ctype object can be called and used as a
647<a href="ext_ffi_api.html#ffi_new">constructor</a>.</li>
648
649<li><b>C&nbsp;function call</b>: a cdata function or cdata function
650pointer can be called. The passed arguments are
651<a href="#convert_fromlua">converted to the C&nbsp;types</a> of the
652parameters given by the function declaration. Arguments passed to the
653variable argument part of vararg C&nbsp;function use
654<a href="#convert_vararg">special conversion rules</a>. This
655C&nbsp;function is called and the return value (if any) is
656<a href="#convert_tolua">converted to a Lua object</a>.</li>
657
658</ul>
659
660<h3 id="cdata_arith">Arithmetic on cdata objects</h3>
661<ul>
662
663<li><b>Pointer arithmetic</b>: a cdata pointer/array and a cdata
664number or a Lua number can be added or subtracted. The number must be
665on the right hand side for a subtraction. The result is a pointer of
666the same type with an address plus or minus the number value
667multiplied by the element size in bytes. An error is raised if the
668element size is undefined.</li>
669
670<li><b>Pointer difference</b>: two compatible cdata pointers/arrays
671can be subtracted. The result is the difference between their
672addresses, divided by the element size in bytes. An error is raised if
673the element size is undefined or zero.</li>
674
675<li><a href="ext_ffi_int64.html">64&nbsp;bit integer arithmetic</a>:
676the standard arithmetic operators
677(<tt>+&nbsp;-&nbsp;*&nbsp;/&nbsp;%&nbsp;^</tt> and unary <tt>-</tt>)
678can be applied to two cdata numbers, or a cdata number and a Lua
679number. If one of them is an <tt>uint64_t</tt>, the other side is
680converted to an <tt>uint64_t</tt> and an unsigned arithmetic operation
681is performed. Otherwise both sides are converted to an
682<tt>int64_t</tt> and a signed arithmetic operation is performed. The
683result is a boxed 64&nbsp;bit cdata object.</li>
684
685</ul>
686
687<h3 id="cdata_comp">Comparisons of cdata objects</h3>
688<ul>
689
690<li><b>Pointer comparison</b>: two compatible cdata pointers/arrays
691can be compared. The result is the same as an unsigned comparison of
692their addresses. <tt>nil</tt> is treated like a <tt>NULL</tt> pointer,
693which is compatible with any other pointer type.</li>
694
695<li><a href="ext_ffi_int64.html">64&nbsp;bit integer comparison</a>:
696two cdata numbers, or a cdata number and a Lua number can be compared
697with each other. If one of them is an <tt>uint64_t</tt>, the other
698side is converted to an <tt>uint64_t</tt> and an unsigned comparison
699is performed. Otherwise both sides are converted to an
700<tt>int64_t</tt> and a signed comparison is performed.</li>
701
702</ul>
703
704<h3 id="cdata_key">cdata objects as table keys</h3>
705<p>
706Lua tables may be indexed by cdata objects, but this doesn't provide
707any useful semantics &mdash; <b>cdata objects are unsuitable as table
708keys!</b>
709</p>
710<p>
711A cdata object is treated like any other garbage-collected object and
712is hashed and compared by its address for table indexing. Since
713there's no interning for cdata value types, the same value may be
714boxed in different cdata objects with different addresses. Thus
715<tt>t[1LL+1LL]</tt> and <tt>t[2LL]</tt> usually <b>do not</b> point to
716the same hash slot and they certainly <b>do not</b> point to the same
717hash slot as <tt>t[2]</tt>.
718</p>
719<p>
720It would seriously drive up implementation complexity and slow down
721the common case, if one were to add extra handling for by-value
722hashing and comparisons to Lua tables. Given the ubiquity of their use
723inside the VM, this is not acceptable.
724</p>
725<p>
726There are three viable alternatives, if you really need to use cdata
727objects as keys:
728</p>
729<ul>
730
731<li>If you can get by with the precision of Lua numbers
732(52&nbsp;bits), then use <tt>tonumber()</tt> on a cdata number or
733combine multiple fields of a cdata aggregate to a Lua number. Then use
734the resulting Lua number as a key when indexing tables.<br>
735One obvious benefit: <tt>t[tonumber(2LL)]</tt> <b>does</b> point to
736the same slot as <tt>t[2]</tt>.</li>
737
738<li>Otherwise use either <tt>tostring()</tt> on 64&nbsp;bit integers
739or complex numbers or combine multiple fields of a cdata aggregate to
740a Lua string (e.g. with
741<a href="ext_ffi_api.html#ffi_string"><tt>ffi.string()</tt></a>). Then
742use the resulting Lua string as a key when indexing tables.</li>
743
744<li>Create your own specialized hash table implementation using the
745C&nbsp;types provided by the FFI library, just like you would in
746C&nbsp;code. Ultimately this may give much better performance than the
747other alternatives or what a generic by-value hash table could
748possibly provide.</li>
749
750</ul>
259 751
260<h2 id="gc">Garbage Collection of cdata Objects</h2> 752<h2 id="gc">Garbage Collection of cdata Objects</h2>
261<p> 753<p>
@@ -297,14 +789,9 @@ is not garbage collected.
297Objects which are passed as an argument to an external C&nbsp;function 789Objects which are passed as an argument to an external C&nbsp;function
298are kept alive until the call returns. So it's generally safe to 790are kept alive until the call returns. So it's generally safe to
299create temporary cdata objects in argument lists. This is a common 791create temporary cdata objects in argument lists. This is a common
300idiom for passing specific C&nbsp;types to vararg functions: 792idiom for <a href="#convert_vararg">passing specific C&nbsp;types to
793vararg functions</a>.
301</p> 794</p>
302<pre class="code">
303ffi.cdef[[
304int printf(const char *fmt, ...);
305]]
306ffi.C.printf("integer value: %d\n", ffi.new("int", x)) -- <span style="color:#00a000;">OK</span>
307</pre>
308<p> 795<p>
309Memory areas returned by C functions (e.g. from <tt>malloc()</tt>) 796Memory areas returned by C functions (e.g. from <tt>malloc()</tt>)
310must be manually managed, of course. Pointers to cdata objects are 797must be manually managed, of course. Pointers to cdata objects are
@@ -468,12 +955,12 @@ suboptimal performance, especially when used in inner loops:
468<li>Array/<tt>struct</tt> copies and bulk initializations.</li> 955<li>Array/<tt>struct</tt> copies and bulk initializations.</li>
469<li>Bitfield accesses and initializations.</li> 956<li>Bitfield accesses and initializations.</li>
470<li>Vector operations.</li> 957<li>Vector operations.</li>
471<li>Lua tables as compound initializers.</li> 958<li>Table initializers.</li>
472<li>Initialization of nested <tt>struct</tt>/<tt>union</tt> types.</li> 959<li>Initialization of nested <tt>struct</tt>/<tt>union</tt> types.</li>
473<li>Allocations of variable-length arrays or structs.</li> 960<li>Allocations of variable-length arrays or structs.</li>
474<li>Allocations of C&nbsp;types with a size &gt; 64&nbsp;bytes or an 961<li>Allocations of C&nbsp;types with a size &gt; 64&nbsp;bytes or an
475alignment &gt; 8&nbsp;bytes.</li> 962alignment &gt; 8&nbsp;bytes.</li>
476<li>Conversions from <tt>lightuserdata</tt> to <tt>void&nbsp;*</tt>.</li> 963<li>Conversions from lightuserdata to <tt>void&nbsp;*</tt>.</li>
477<li>Pointer differences for element sizes that are not a power of 964<li>Pointer differences for element sizes that are not a power of
478two.</li> 965two.</li>
479<li>Calls to non-cdecl or vararg C&nbsp;functions.</li> 966<li>Calls to non-cdecl or vararg C&nbsp;functions.</li>
@@ -496,7 +983,7 @@ Other missing features:
496<li>Callbacks from C&nbsp;code to Lua functions.</li> 983<li>Callbacks from C&nbsp;code to Lua functions.</li>
497<li>Atomic handling of <tt>errno</tt>.</li> 984<li>Atomic handling of <tt>errno</tt>.</li>
498<li>Passing structs by value to vararg C&nbsp;functions.</li> 985<li>Passing structs by value to vararg C&nbsp;functions.</li>
499<li><a href="extensions.html#exceptions">C++ exception interoperability<a/> 986<li><a href="extensions.html#exceptions">C++ exception interoperability</a>
500does not extend to C&nbsp;functions called via the FFI.</li> 987does not extend to C&nbsp;functions called via the FFI.</li>
501</ul> 988</ul>
502<br class="flush"> 989<br class="flush">