| 1 | <!DOCTYPE html> |
| 2 | <html> |
| 3 | <head> |
| 4 | <title>FFI Semantics</title> |
| 5 | <meta charset="utf-8"> |
| 6 | <meta name="Copyright" content="Copyright (C) 2005-2025"> |
| 7 | <meta name="Language" content="en"> |
| 8 | <link rel="stylesheet" type="text/css" href="bluequad.css" media="screen"> |
| 9 | <link rel="stylesheet" type="text/css" href="bluequad-print.css" media="print"> |
| 10 | <style type="text/css"> |
| 11 | table.convtable { line-height: 1.2; } |
| 12 | tr.convhead td { font-weight: bold; } |
| 13 | td.convop { font-style: italic; width: 40%; } |
| 14 | </style> |
| 15 | </head> |
| 16 | <body> |
| 17 | <div id="site"> |
| 18 | <a href="https://luajit.org"><span>Lua<span id="logo">JIT</span></span></a> |
| 19 | </div> |
| 20 | <div id="head"> |
| 21 | <h1>FFI Semantics</h1> |
| 22 | </div> |
| 23 | <div id="nav"> |
| 24 | <ul><li> |
| 25 | <a href="luajit.html">LuaJIT</a> |
| 26 | <ul><li> |
| 27 | <a href="https://luajit.org/download.html">Download <span class="ext">»</span></a> |
| 28 | </li><li> |
| 29 | <a href="install.html">Installation</a> |
| 30 | </li><li> |
| 31 | <a href="running.html">Running</a> |
| 32 | </li></ul> |
| 33 | </li><li> |
| 34 | <a href="extensions.html">Extensions</a> |
| 35 | <ul><li> |
| 36 | <a href="ext_ffi.html">FFI Library</a> |
| 37 | <ul><li> |
| 38 | <a href="ext_ffi_tutorial.html">FFI Tutorial</a> |
| 39 | </li><li> |
| 40 | <a href="ext_ffi_api.html">ffi.* API</a> |
| 41 | </li><li> |
| 42 | <a class="current" href="ext_ffi_semantics.html">FFI Semantics</a> |
| 43 | </li></ul> |
| 44 | </li><li> |
| 45 | <a href="ext_buffer.html">String Buffers</a> |
| 46 | </li><li> |
| 47 | <a href="ext_jit.html">jit.* Library</a> |
| 48 | </li><li> |
| 49 | <a href="ext_c_api.html">Lua/C API</a> |
| 50 | </li><li> |
| 51 | <a href="ext_profiler.html">Profiler</a> |
| 52 | </li></ul> |
| 53 | </li><li> |
| 54 | <a href="https://luajit.org/status.html">Status <span class="ext">»</span></a> |
| 55 | </li><li> |
| 56 | <a href="https://luajit.org/faq.html">FAQ <span class="ext">»</span></a> |
| 57 | </li><li> |
| 58 | <a href="https://luajit.org/list.html">Mailing List <span class="ext">»</span></a> |
| 59 | </li></ul> |
| 60 | </div> |
| 61 | <div id="main"> |
| 62 | <p> |
| 63 | This page describes the detailed semantics underlying the FFI library |
| 64 | and its interaction with both Lua and C code. |
| 65 | </p> |
| 66 | <p> |
| 67 | Given that the FFI library is designed to interface with C code |
| 68 | and that declarations can be written in plain C syntax, <b>it |
| 69 | closely follows the C language semantics</b>, wherever possible. |
| 70 | Some minor concessions are needed for smoother interoperation with Lua |
| 71 | language semantics. |
| 72 | </p> |
| 73 | <p> |
| 74 | Please don't be overwhelmed by the contents of this page — this |
| 75 | is a reference and you may need to consult it, if in doubt. It doesn't |
| 76 | hurt to skim this page, but most of the semantics "just work" as you'd |
| 77 | expect them to work. It should be straightforward to write |
| 78 | applications using the LuaJIT FFI for developers with a C or C++ |
| 79 | background. |
| 80 | </p> |
| 81 | |
| 82 | <h2 id="clang">C Language Support</h2> |
| 83 | <p> |
| 84 | The FFI library has a built-in C parser with a minimal memory |
| 85 | footprint. It's used by the <a href="ext_ffi_api.html">ffi.* library |
| 86 | functions</a> to declare C types or external symbols. |
| 87 | </p> |
| 88 | <p> |
| 89 | Its only purpose is to parse C declarations, as found e.g. in |
| 90 | C header files. Although it does evaluate constant expressions, |
| 91 | it's <em>not</em> a C compiler. The body of <tt>inline</tt> |
| 92 | C function definitions is simply ignored. |
| 93 | </p> |
| 94 | <p> |
| 95 | Also, this is <em>not</em> a validating C parser. It expects and |
| 96 | accepts correctly formed C declarations, but it may choose to |
| 97 | ignore bad declarations or show rather generic error messages. If in |
| 98 | doubt, please check the input against your favorite C compiler. |
| 99 | </p> |
| 100 | <p> |
| 101 | The C parser complies to the <b>C99 language standard</b> plus |
| 102 | the following extensions: |
| 103 | </p> |
| 104 | <ul> |
| 105 | |
| 106 | <li>The <tt>'\e'</tt> escape in character and string literals.</li> |
| 107 | |
| 108 | <li>The C99/C++ boolean type, declared with the keywords <tt>bool</tt> |
| 109 | or <tt>_Bool</tt>.</li> |
| 110 | |
| 111 | <li>Complex numbers, declared with the keywords <tt>complex</tt> or |
| 112 | <tt>_Complex</tt>.</li> |
| 113 | |
| 114 | <li>Two complex number types: <tt>complex</tt> (aka |
| 115 | <tt>complex double</tt>) and <tt>complex float</tt>.</li> |
| 116 | |
| 117 | <li>Vector types, declared with the GCC <tt>mode</tt> or |
| 118 | <tt>vector_size</tt> attribute.</li> |
| 119 | |
| 120 | <li>Unnamed ('transparent') <tt>struct</tt>/<tt>union</tt> fields |
| 121 | inside a <tt>struct</tt>/<tt>union</tt>.</li> |
| 122 | |
| 123 | <li>Incomplete <tt>enum</tt> declarations, handled like incomplete |
| 124 | <tt>struct</tt> declarations.</li> |
| 125 | |
| 126 | <li>Unnamed <tt>enum</tt> fields inside a |
| 127 | <tt>struct</tt>/<tt>union</tt>. This is similar to a scoped C++ |
| 128 | <tt>enum</tt>, except that declared constants are visible in the |
| 129 | global namespace, too.</li> |
| 130 | |
| 131 | <li>Scoped <tt>static const</tt> declarations inside a |
| 132 | <tt>struct</tt>/<tt>union</tt> (from C++).</li> |
| 133 | |
| 134 | <li>Zero-length arrays (<tt>[0]</tt>), empty |
| 135 | <tt>struct</tt>/<tt>union</tt>, variable-length arrays (VLA, |
| 136 | <tt>[?]</tt>) and variable-length structs (VLS, with a trailing |
| 137 | VLA).</li> |
| 138 | |
| 139 | <li>C++ reference types (<tt>int &x</tt>).</li> |
| 140 | |
| 141 | <li>Alternate GCC keywords with '<tt>__</tt>', e.g. |
| 142 | <tt>__const__</tt>.</li> |
| 143 | |
| 144 | <li>GCC <tt>__attribute__</tt> with the following attributes: |
| 145 | <tt>aligned</tt>, <tt>packed</tt>, <tt>mode</tt>, |
| 146 | <tt>vector_size</tt>, <tt>cdecl</tt>, <tt>fastcall</tt>, |
| 147 | <tt>stdcall</tt>, <tt>thiscall</tt>.</li> |
| 148 | |
| 149 | <li>The GCC <tt>__extension__</tt> keyword and the GCC |
| 150 | <tt>__alignof__</tt> operator.</li> |
| 151 | |
| 152 | <li>GCC <tt>__asm__("symname")</tt> symbol name redirection for |
| 153 | function declarations.</li> |
| 154 | |
| 155 | <li>MSVC keywords for fixed-length types: <tt>__int8</tt>, |
| 156 | <tt>__int16</tt>, <tt>__int32</tt> and <tt>__int64</tt>.</li> |
| 157 | |
| 158 | <li>MSVC <tt>__cdecl</tt>, <tt>__fastcall</tt>, <tt>__stdcall</tt>, |
| 159 | <tt>__thiscall</tt>, <tt>__ptr32</tt>, <tt>__ptr64</tt>, |
| 160 | <tt>__declspec(align(n))</tt> and <tt>#pragma pack</tt>.</li> |
| 161 | |
| 162 | <li>All other GCC/MSVC-specific attributes are ignored.</li> |
| 163 | |
| 164 | </ul> |
| 165 | <p> |
| 166 | The following C types are predefined by the C parser (like |
| 167 | a <tt>typedef</tt>, except re-declarations will be ignored): |
| 168 | </p> |
| 169 | <ul> |
| 170 | |
| 171 | <li>Vararg handling: <tt>va_list</tt>, <tt>__builtin_va_list</tt>, |
| 172 | <tt>__gnuc_va_list</tt>.</li> |
| 173 | |
| 174 | <li>From <tt><stddef.h></tt>: <tt>ptrdiff_t</tt>, |
| 175 | <tt>size_t</tt>, <tt>wchar_t</tt>.</li> |
| 176 | |
| 177 | <li>From <tt><stdint.h></tt>: <tt>int8_t</tt>, <tt>int16_t</tt>, |
| 178 | <tt>int32_t</tt>, <tt>int64_t</tt>, <tt>uint8_t</tt>, |
| 179 | <tt>uint16_t</tt>, <tt>uint32_t</tt>, <tt>uint64_t</tt>, |
| 180 | <tt>intptr_t</tt>, <tt>uintptr_t</tt>.</li> |
| 181 | |
| 182 | <li>From <tt><unistd.h></tt> (POSIX): <tt>ssize_t</tt>.</li> |
| 183 | |
| 184 | </ul> |
| 185 | <p> |
| 186 | You're encouraged to use these types in preference to |
| 187 | compiler-specific extensions or target-dependent standard types. |
| 188 | E.g. <tt>char</tt> differs in signedness and <tt>long</tt> differs in |
| 189 | size, depending on the target architecture and platform ABI. |
| 190 | </p> |
| 191 | <p> |
| 192 | The following C features are <b>not</b> supported: |
| 193 | </p> |
| 194 | <ul> |
| 195 | |
| 196 | <li>A declaration must always have a type specifier; it doesn't |
| 197 | default to an <tt>int</tt> type.</li> |
| 198 | |
| 199 | <li>Old-style empty function declarations (K&R) are not allowed. |
| 200 | All C functions must have a proper prototype declaration. A |
| 201 | function declared without parameters (<tt>int foo();</tt>) is |
| 202 | treated as a function taking zero arguments, like in C++.</li> |
| 203 | |
| 204 | <li>The <tt>long double</tt> C type is parsed correctly, but |
| 205 | there's no support for the related conversions, accesses or arithmetic |
| 206 | operations.</li> |
| 207 | |
| 208 | <li>Wide character strings and character literals are not |
| 209 | supported.</li> |
| 210 | |
| 211 | <li><a href="#status">See below</a> for features that are currently |
| 212 | not implemented.</li> |
| 213 | |
| 214 | </ul> |
| 215 | |
| 216 | <h2 id="convert">C Type Conversion Rules</h2> |
| 217 | |
| 218 | <h3 id="convert_tolua">Conversions from C types to Lua objects</h3> |
| 219 | <p> |
| 220 | These conversion rules apply for <em>read accesses</em> to |
| 221 | C types: indexing pointers, arrays or |
| 222 | <tt>struct</tt>/<tt>union</tt> types; reading external variables or |
| 223 | constant values; retrieving return values from C calls: |
| 224 | </p> |
| 225 | <table class="convtable"> |
| 226 | <tr class="convhead"> |
| 227 | <td class="convin">Input</td> |
| 228 | <td class="convop">Conversion</td> |
| 229 | <td class="convout">Output</td> |
| 230 | </tr> |
| 231 | <tr class="odd separate"> |
| 232 | <td class="convin"><tt>int8_t</tt>, <tt>int16_t</tt></td><td class="convop">→<sup>sign-ext</sup> <tt>int32_t</tt> → <tt>double</tt></td><td class="convout">number</td></tr> |
| 233 | <tr class="even"> |
| 234 | <td class="convin"><tt>uint8_t</tt>, <tt>uint16_t</tt></td><td class="convop">→<sup>zero-ext</sup> <tt>int32_t</tt> → <tt>double</tt></td><td class="convout">number</td></tr> |
| 235 | <tr class="odd"> |
| 236 | <td class="convin"><tt>int32_t</tt>, <tt>uint32_t</tt></td><td class="convop">→ <tt>double</tt></td><td class="convout">number</td></tr> |
| 237 | <tr class="even"> |
| 238 | <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> |
| 239 | <tr class="odd separate"> |
| 240 | <td class="convin"><tt>double</tt>, <tt>float</tt></td><td class="convop">→ <tt>double</tt></td><td class="convout">number</td></tr> |
| 241 | <tr class="even separate"> |
| 242 | <td class="convin"><tt>bool</tt></td><td class="convop">0 → <tt>false</tt>, otherwise <tt>true</tt></td><td class="convout">boolean</td></tr> |
| 243 | <tr class="odd separate"> |
| 244 | <td class="convin"><tt>enum</tt></td><td class="convop">boxed value</td><td class="convout">enum cdata</td></tr> |
| 245 | <tr class="even"> |
| 246 | <td class="convin">Complex number</td><td class="convop">boxed value</td><td class="convout">complex cdata</td></tr> |
| 247 | <tr class="odd"> |
| 248 | <td class="convin">Vector</td><td class="convop">boxed value</td><td class="convout">vector cdata</td></tr> |
| 249 | <tr class="even"> |
| 250 | <td class="convin">Pointer</td><td class="convop">boxed value</td><td class="convout">pointer cdata</td></tr> |
| 251 | <tr class="odd separate"> |
| 252 | <td class="convin">Array</td><td class="convop">boxed reference</td><td class="convout">reference cdata</td></tr> |
| 253 | <tr class="even"> |
| 254 | <td class="convin"><tt>struct</tt>/<tt>union</tt></td><td class="convop">boxed reference</td><td class="convout">reference cdata</td></tr> |
| 255 | </table> |
| 256 | <p> |
| 257 | Bitfields are treated like their underlying type. |
| 258 | </p> |
| 259 | <p> |
| 260 | Reference types are dereferenced <em>before</em> a conversion can take |
| 261 | place — the conversion is applied to the C type pointed to |
| 262 | by the reference. |
| 263 | </p> |
| 264 | |
| 265 | <h3 id="convert_fromlua">Conversions from Lua objects to C types</h3> |
| 266 | <p> |
| 267 | These conversion rules apply for <em>write accesses</em> to |
| 268 | C types: indexing pointers, arrays or |
| 269 | <tt>struct</tt>/<tt>union</tt> types; initializing cdata objects; |
| 270 | casts to C types; writing to external variables; passing |
| 271 | arguments to C calls: |
| 272 | </p> |
| 273 | <table class="convtable"> |
| 274 | <tr class="convhead"> |
| 275 | <td class="convin">Input</td> |
| 276 | <td class="convop">Conversion</td> |
| 277 | <td class="convout">Output</td> |
| 278 | </tr> |
| 279 | <tr class="odd separate"> |
| 280 | <td class="convin">number</td><td class="convop">→</td><td class="convout"><tt>double</tt></td></tr> |
| 281 | <tr class="even"> |
| 282 | <td class="convin">boolean</td><td class="convop"><tt>false</tt> → 0, <tt>true</tt> → 1</td><td class="convout"><tt>bool</tt></td></tr> |
| 283 | <tr class="odd separate"> |
| 284 | <td class="convin">nil</td><td class="convop"><tt>NULL</tt> →</td><td class="convout"><tt>(void *)</tt></td></tr> |
| 285 | <tr class="even"> |
| 286 | <td class="convin">lightuserdata</td><td class="convop">lightuserdata address →</td><td class="convout"><tt>(void *)</tt></td></tr> |
| 287 | <tr class="odd"> |
| 288 | <td class="convin">userdata</td><td class="convop">userdata payload →</td><td class="convout"><tt>(void *)</tt></td></tr> |
| 289 | <tr class="even"> |
| 290 | <td class="convin">io.* file</td><td class="convop">get FILE * handle →</td><td class="convout"><tt>(void *)</tt></td></tr> |
| 291 | <tr class="odd separate"> |
| 292 | <td class="convin">string</td><td class="convop">match against <tt>enum</tt> constant</td><td class="convout"><tt>enum</tt></td></tr> |
| 293 | <tr class="even"> |
| 294 | <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> |
| 295 | <tr class="odd"> |
| 296 | <td class="convin">string</td><td class="convop">string data →</td><td class="convout"><tt>const char[]</tt></td></tr> |
| 297 | <tr class="even separate"> |
| 298 | <td class="convin">function</td><td class="convop"><a href="#callback">create callback</a> →</td><td class="convout">C function type</td></tr> |
| 299 | <tr class="odd separate"> |
| 300 | <td class="convin">table</td><td class="convop"><a href="#init_table">table initializer</a></td><td class="convout">Array</td></tr> |
| 301 | <tr class="even"> |
| 302 | <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> |
| 303 | <tr class="odd separate"> |
| 304 | <td class="convin">cdata</td><td class="convop">cdata payload →</td><td class="convout">C type</td></tr> |
| 305 | </table> |
| 306 | <p> |
| 307 | If the result type of this conversion doesn't match the |
| 308 | C type of the destination, the |
| 309 | <a href="#convert_between">conversion rules between C types</a> |
| 310 | are applied. |
| 311 | </p> |
| 312 | <p> |
| 313 | Reference types are immutable after initialization ("no re-seating of |
| 314 | references"). For initialization purposes or when passing values to |
| 315 | reference parameters, they are treated like pointers. Note that unlike |
| 316 | in C++, there's no way to implement automatic reference generation of |
| 317 | variables under the Lua language semantics. If you want to call a |
| 318 | function with a reference parameter, you need to explicitly pass a |
| 319 | one-element array. |
| 320 | </p> |
| 321 | |
| 322 | <h3 id="convert_between">Conversions between C types</h3> |
| 323 | <p> |
| 324 | These conversion rules are more or less the same as the standard |
| 325 | C conversion rules. Some rules only apply to casts, or require |
| 326 | pointer or type compatibility: |
| 327 | </p> |
| 328 | <table class="convtable"> |
| 329 | <tr class="convhead"> |
| 330 | <td class="convin">Input</td> |
| 331 | <td class="convop">Conversion</td> |
| 332 | <td class="convout">Output</td> |
| 333 | </tr> |
| 334 | <tr class="odd separate"> |
| 335 | <td class="convin">Signed integer</td><td class="convop">→<sup>narrow or sign-extend</sup></td><td class="convout">Integer</td></tr> |
| 336 | <tr class="even"> |
| 337 | <td class="convin">Unsigned integer</td><td class="convop">→<sup>narrow or zero-extend</sup></td><td class="convout">Integer</td></tr> |
| 338 | <tr class="odd"> |
| 339 | <td class="convin">Integer</td><td class="convop">→<sup>round</sup></td><td class="convout"><tt>double</tt>, <tt>float</tt></td></tr> |
| 340 | <tr class="even"> |
| 341 | <td class="convin"><tt>double</tt>, <tt>float</tt></td><td class="convop">→<sup>trunc</sup> <tt>int32_t</tt> →<sup>narrow</sup></td><td class="convout"><tt>(u)int8_t</tt>, <tt>(u)int16_t</tt></td></tr> |
| 342 | <tr class="odd"> |
| 343 | <td class="convin"><tt>double</tt>, <tt>float</tt></td><td class="convop">→<sup>trunc</sup></td><td class="convout"><tt>(u)int32_t</tt>, <tt>(u)int64_t</tt></td></tr> |
| 344 | <tr class="even"> |
| 345 | <td class="convin"><tt>double</tt>, <tt>float</tt></td><td class="convop">→<sup>round</sup></td><td class="convout"><tt>float</tt>, <tt>double</tt></td></tr> |
| 346 | <tr class="odd separate"> |
| 347 | <td class="convin">Number</td><td class="convop">n == 0 → 0, otherwise 1</td><td class="convout"><tt>bool</tt></td></tr> |
| 348 | <tr class="even"> |
| 349 | <td class="convin"><tt>bool</tt></td><td class="convop"><tt>false</tt> → 0, <tt>true</tt> → 1</td><td class="convout">Number</td></tr> |
| 350 | <tr class="odd separate"> |
| 351 | <td class="convin">Complex number</td><td class="convop">convert real part</td><td class="convout">Number</td></tr> |
| 352 | <tr class="even"> |
| 353 | <td class="convin">Number</td><td class="convop">convert real part, imag = 0</td><td class="convout">Complex number</td></tr> |
| 354 | <tr class="odd"> |
| 355 | <td class="convin">Complex number</td><td class="convop">convert real and imag part</td><td class="convout">Complex number</td></tr> |
| 356 | <tr class="even separate"> |
| 357 | <td class="convin">Number</td><td class="convop">convert scalar and replicate</td><td class="convout">Vector</td></tr> |
| 358 | <tr class="odd"> |
| 359 | <td class="convin">Vector</td><td class="convop">copy (same size)</td><td class="convout">Vector</td></tr> |
| 360 | <tr class="even separate"> |
| 361 | <td class="convin"><tt>struct</tt>/<tt>union</tt></td><td class="convop">take base address (compat)</td><td class="convout">Pointer</td></tr> |
| 362 | <tr class="odd"> |
| 363 | <td class="convin">Array</td><td class="convop">take base address (compat)</td><td class="convout">Pointer</td></tr> |
| 364 | <tr class="even"> |
| 365 | <td class="convin">Function</td><td class="convop">take function address</td><td class="convout">Function pointer</td></tr> |
| 366 | <tr class="odd separate"> |
| 367 | <td class="convin">Number</td><td class="convop">convert via <tt>uintptr_t</tt> (cast)</td><td class="convout">Pointer</td></tr> |
| 368 | <tr class="even"> |
| 369 | <td class="convin">Pointer</td><td class="convop">convert address (compat/cast)</td><td class="convout">Pointer</td></tr> |
| 370 | <tr class="odd"> |
| 371 | <td class="convin">Pointer</td><td class="convop">convert address (cast)</td><td class="convout">Integer</td></tr> |
| 372 | <tr class="even"> |
| 373 | <td class="convin">Array</td><td class="convop">convert base address (cast)</td><td class="convout">Integer</td></tr> |
| 374 | <tr class="odd separate"> |
| 375 | <td class="convin">Array</td><td class="convop">copy (compat)</td><td class="convout">Array</td></tr> |
| 376 | <tr class="even"> |
| 377 | <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> |
| 378 | </table> |
| 379 | <p> |
| 380 | Bitfields or <tt>enum</tt> types are treated like their underlying |
| 381 | type. |
| 382 | </p> |
| 383 | <p> |
| 384 | Conversions not listed above will raise an error. E.g. it's not |
| 385 | possible to convert a pointer to a complex number or vice versa. |
| 386 | </p> |
| 387 | |
| 388 | <h3 id="convert_vararg">Conversions for vararg C function arguments</h3> |
| 389 | <p> |
| 390 | The following default conversion rules apply when passing Lua objects |
| 391 | to the variable argument part of vararg C functions: |
| 392 | </p> |
| 393 | <table class="convtable"> |
| 394 | <tr class="convhead"> |
| 395 | <td class="convin">Input</td> |
| 396 | <td class="convop">Conversion</td> |
| 397 | <td class="convout">Output</td> |
| 398 | </tr> |
| 399 | <tr class="odd separate"> |
| 400 | <td class="convin">number</td><td class="convop">→</td><td class="convout"><tt>double</tt></td></tr> |
| 401 | <tr class="even"> |
| 402 | <td class="convin">boolean</td><td class="convop"><tt>false</tt> → 0, <tt>true</tt> → 1</td><td class="convout"><tt>bool</tt></td></tr> |
| 403 | <tr class="odd separate"> |
| 404 | <td class="convin">nil</td><td class="convop"><tt>NULL</tt> →</td><td class="convout"><tt>(void *)</tt></td></tr> |
| 405 | <tr class="even"> |
| 406 | <td class="convin">userdata</td><td class="convop">userdata payload →</td><td class="convout"><tt>(void *)</tt></td></tr> |
| 407 | <tr class="odd"> |
| 408 | <td class="convin">lightuserdata</td><td class="convop">lightuserdata address →</td><td class="convout"><tt>(void *)</tt></td></tr> |
| 409 | <tr class="even separate"> |
| 410 | <td class="convin">string</td><td class="convop">string data →</td><td class="convout"><tt>const char *</tt></td></tr> |
| 411 | <tr class="odd separate"> |
| 412 | <td class="convin"><tt>float</tt> cdata</td><td class="convop">→</td><td class="convout"><tt>double</tt></td></tr> |
| 413 | <tr class="even"> |
| 414 | <td class="convin">Array cdata</td><td class="convop">take base address</td><td class="convout">Element pointer</td></tr> |
| 415 | <tr class="odd"> |
| 416 | <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> |
| 417 | <tr class="even"> |
| 418 | <td class="convin">Function cdata</td><td class="convop">take function address</td><td class="convout">Function pointer</td></tr> |
| 419 | <tr class="odd"> |
| 420 | <td class="convin">Any other cdata</td><td class="convop">no conversion</td><td class="convout">C type</td></tr> |
| 421 | </table> |
| 422 | <p> |
| 423 | To pass a Lua object, other than a cdata object, as a specific type, |
| 424 | you need to override the conversion rules: create a temporary cdata |
| 425 | object with a constructor or a cast and initialize it with the value |
| 426 | to pass: |
| 427 | </p> |
| 428 | <p> |
| 429 | Assuming <tt>x</tt> is a Lua number, here's how to pass it as an |
| 430 | integer to a vararg function: |
| 431 | </p> |
| 432 | <pre class="code"> |
| 433 | ffi.cdef[[ |
| 434 | int printf(const char *fmt, ...); |
| 435 | ]] |
| 436 | ffi.C.printf("integer value: %d\n", ffi.new("int", x)) |
| 437 | </pre> |
| 438 | <p> |
| 439 | If you don't do this, the default Lua number → <tt>double</tt> |
| 440 | conversion rule applies. A vararg C function expecting an integer |
| 441 | will see a garbled or uninitialized value. |
| 442 | </p> |
| 443 | <p> |
| 444 | Note: this is the only place where creating a boxed scalar number type is |
| 445 | actually useful. <b>Never use <tt>ffi.new("int")</tt>, <tt>ffi.new("float")</tt> |
| 446 | etc. anywhere else!</b> |
| 447 | </p> |
| 448 | <p style="font-size: 8pt;"> |
| 449 | Ditto for <tt>ffi.cast()</tt>. Explicitly boxing scalars <b>does not</b> |
| 450 | improve performance or force <tt>int</tt> or <tt>float</tt> arithmetic! It |
| 451 | just adds costly boxing, unboxing and conversions steps. And it may lead |
| 452 | to surprise results, because |
| 453 | <a href="#cdata_arith">cdata arithmetic on scalar numbers</a> |
| 454 | is always performed on 64 bit integers. |
| 455 | </p> |
| 456 | |
| 457 | <h2 id="init">Initializers</h2> |
| 458 | <p> |
| 459 | Creating a cdata object with |
| 460 | <a href="ext_ffi_api.html#ffi_new"><tt>ffi.new()</tt></a> or the |
| 461 | equivalent constructor syntax always initializes its contents, too. |
| 462 | Different rules apply, depending on the number of optional |
| 463 | initializers and the C types involved: |
| 464 | </p> |
| 465 | <ul> |
| 466 | <li>If no initializers are given, the object is filled with zero bytes.</li> |
| 467 | |
| 468 | <li>Scalar types (numbers and pointers) accept a single initializer. |
| 469 | The Lua object is <a href="#convert_fromlua">converted to the scalar |
| 470 | C type</a>.</li> |
| 471 | |
| 472 | <li>Valarrays (complex numbers and vectors) are treated like scalars |
| 473 | when a single initializer is given. Otherwise they are treated like |
| 474 | regular arrays.</li> |
| 475 | |
| 476 | <li>Aggregate types (arrays and structs) accept either a single cdata |
| 477 | initializer of the same type (copy constructor), a single |
| 478 | <a href="#init_table">table initializer</a>, or a flat list of |
| 479 | initializers.</li> |
| 480 | |
| 481 | <li>The elements of an array are initialized, starting at index zero. |
| 482 | If a single initializer is given for an array, it's repeated for all |
| 483 | remaining elements. This doesn't happen if two or more initializers |
| 484 | are given: all remaining uninitialized elements are filled with zero |
| 485 | bytes.</li> |
| 486 | |
| 487 | <li>Byte arrays may also be initialized with a Lua string. This copies |
| 488 | the whole string plus a terminating zero-byte. The copy stops early only |
| 489 | if the array has a known, fixed size.</li> |
| 490 | |
| 491 | <li>The fields of a <tt>struct</tt> are initialized in the order of |
| 492 | their declaration. Uninitialized fields are filled with zero |
| 493 | bytes.</li> |
| 494 | |
| 495 | <li>Only the first field of a <tt>union</tt> can be initialized with a |
| 496 | flat initializer.</li> |
| 497 | |
| 498 | <li>Elements or fields which are aggregates themselves are initialized |
| 499 | with a <em>single</em> initializer, but this may be a table |
| 500 | initializer or a compatible aggregate.</li> |
| 501 | |
| 502 | <li>Excess initializers cause an error.</li> |
| 503 | |
| 504 | </ul> |
| 505 | |
| 506 | <h2 id="init_table">Table Initializers</h2> |
| 507 | <p> |
| 508 | The following rules apply if a Lua table is used to initialize an |
| 509 | Array or a <tt>struct</tt>/<tt>union</tt>: |
| 510 | </p> |
| 511 | <ul> |
| 512 | |
| 513 | <li>If the table index <tt>[0]</tt> is non-<tt>nil</tt>, then the |
| 514 | table is assumed to be zero-based. Otherwise it's assumed to be |
| 515 | one-based.</li> |
| 516 | |
| 517 | <li>Array elements, starting at index zero, are initialized one-by-one |
| 518 | with the consecutive table elements, starting at either index |
| 519 | <tt>[0]</tt> or <tt>[1]</tt>. This process stops at the first |
| 520 | <tt>nil</tt> table element.</li> |
| 521 | |
| 522 | <li>If exactly one array element was initialized, it's repeated for |
| 523 | all the remaining elements. Otherwise all remaining uninitialized |
| 524 | elements are filled with zero bytes.</li> |
| 525 | |
| 526 | <li>The above logic only applies to arrays with a known fixed size. |
| 527 | A VLA is only initialized with the element(s) given in the table. |
| 528 | Depending on the use case, you may need to explicitly add a |
| 529 | <tt>NULL</tt> or <tt>0</tt> terminator to a VLA.</li> |
| 530 | |
| 531 | <li>A <tt>struct</tt>/<tt>union</tt> can be initialized in the |
| 532 | order of the declaration of its fields. Each field is initialized with |
| 533 | consecutive table elements, starting at either index <tt>[0]</tt> |
| 534 | or <tt>[1]</tt>. This process stops at the first <tt>nil</tt> table |
| 535 | element.</li> |
| 536 | |
| 537 | <li>Otherwise, if neither index <tt>[0]</tt> nor <tt>[1]</tt> is present, |
| 538 | a <tt>struct</tt>/<tt>union</tt> is initialized by looking up each field |
| 539 | name (as a string key) in the table. Each non-<tt>nil</tt> value is |
| 540 | used to initialize the corresponding field.</li> |
| 541 | |
| 542 | <li>Uninitialized fields of a <tt>struct</tt> are filled with zero |
| 543 | bytes, except for the trailing VLA of a VLS.</li> |
| 544 | |
| 545 | <li>Initialization of a <tt>union</tt> stops after one field has been |
| 546 | initialized. If no field has been initialized, the <tt>union</tt> is |
| 547 | filled with zero bytes.</li> |
| 548 | |
| 549 | <li>Elements or fields which are aggregates themselves are initialized |
| 550 | with a <em>single</em> initializer, but this may be a nested table |
| 551 | initializer (or a compatible aggregate).</li> |
| 552 | |
| 553 | <li>Excess initializers for an array cause an error. Excess |
| 554 | initializers for a <tt>struct</tt>/<tt>union</tt> are ignored. |
| 555 | Unrelated table entries are ignored, too.</li> |
| 556 | |
| 557 | </ul> |
| 558 | <p> |
| 559 | Example: |
| 560 | </p> |
| 561 | <pre class="code"> |
| 562 | local ffi = require("ffi") |
| 563 | |
| 564 | ffi.cdef[[ |
| 565 | struct foo { int a, b; }; |
| 566 | union bar { int i; double d; }; |
| 567 | struct nested { int x; struct foo y; }; |
| 568 | ]] |
| 569 | |
| 570 | ffi.new("int[3]", {}) --> 0, 0, 0 |
| 571 | ffi.new("int[3]", {1}) --> 1, 1, 1 |
| 572 | ffi.new("int[3]", {1,2}) --> 1, 2, 0 |
| 573 | ffi.new("int[3]", {1,2,3}) --> 1, 2, 3 |
| 574 | ffi.new("int[3]", {[0]=1}) --> 1, 1, 1 |
| 575 | ffi.new("int[3]", {[0]=1,2}) --> 1, 2, 0 |
| 576 | ffi.new("int[3]", {[0]=1,2,3}) --> 1, 2, 3 |
| 577 | ffi.new("int[3]", {[0]=1,2,3,4}) --> error: too many initializers |
| 578 | |
| 579 | ffi.new("struct foo", {}) --> a = 0, b = 0 |
| 580 | ffi.new("struct foo", {1}) --> a = 1, b = 0 |
| 581 | ffi.new("struct foo", {1,2}) --> a = 1, b = 2 |
| 582 | ffi.new("struct foo", {[0]=1,2}) --> a = 1, b = 2 |
| 583 | ffi.new("struct foo", {b=2}) --> a = 0, b = 2 |
| 584 | ffi.new("struct foo", {a=1,b=2,c=3}) --> a = 1, b = 2 'c' is ignored |
| 585 | |
| 586 | ffi.new("union bar", {}) --> i = 0, d = 0.0 |
| 587 | ffi.new("union bar", {1}) --> i = 1, d = ? |
| 588 | ffi.new("union bar", {[0]=1,2}) --> i = 1, d = ? '2' is ignored |
| 589 | ffi.new("union bar", {d=2}) --> i = ?, d = 2.0 |
| 590 | |
| 591 | ffi.new("struct nested", {1,{2,3}}) --> x = 1, y.a = 2, y.b = 3 |
| 592 | ffi.new("struct nested", {x=1,y={2,3}}) --> x = 1, y.a = 2, y.b = 3 |
| 593 | </pre> |
| 594 | |
| 595 | <h2 id="cdata_ops">Operations on cdata Objects</h2> |
| 596 | <p> |
| 597 | All standard Lua operators can be applied to cdata objects or a |
| 598 | mix of a cdata object and another Lua object. The following list shows |
| 599 | the predefined operations. |
| 600 | </p> |
| 601 | <p> |
| 602 | Reference types are dereferenced <em>before</em> performing each of |
| 603 | the operations below — the operation is applied to the |
| 604 | C type pointed to by the reference. |
| 605 | </p> |
| 606 | <p> |
| 607 | The predefined operations are always tried first before deferring to a |
| 608 | metamethod or index table (if any) for the corresponding ctype (except |
| 609 | for <tt>__new</tt>). An error is raised if the metamethod lookup or |
| 610 | index table lookup fails. |
| 611 | </p> |
| 612 | |
| 613 | <h3 id="cdata_array">Indexing a cdata object</h3> |
| 614 | <ul> |
| 615 | |
| 616 | <li><b>Indexing a pointer/array</b>: a cdata pointer/array can be |
| 617 | indexed by a cdata number or a Lua number. The element address is |
| 618 | computed as the base address plus the number value multiplied by the |
| 619 | element size in bytes. A read access loads the element value and |
| 620 | <a href="#convert_tolua">converts it to a Lua object</a>. A write |
| 621 | access <a href="#convert_fromlua">converts a Lua object to the element |
| 622 | type</a> and stores the converted value to the element. An error is |
| 623 | raised if the element size is undefined or a write access to a |
| 624 | constant element is attempted.</li> |
| 625 | |
| 626 | <li><b>Dereferencing a <tt>struct</tt>/<tt>union</tt> field</b>: a |
| 627 | cdata <tt>struct</tt>/<tt>union</tt> or a pointer to a |
| 628 | <tt>struct</tt>/<tt>union</tt> can be dereferenced by a string key, |
| 629 | giving the field name. The field address is computed as the base |
| 630 | address plus the relative offset of the field. A read access loads the |
| 631 | field value and <a href="#convert_tolua">converts it to a Lua |
| 632 | object</a>. A write access <a href="#convert_fromlua">converts a Lua |
| 633 | object to the field type</a> and stores the converted value to the |
| 634 | field. An error is raised if a write access to a constant |
| 635 | <tt>struct</tt>/<tt>union</tt> or a constant field is attempted. |
| 636 | Scoped enum constants or static constants are treated like a constant |
| 637 | field.</li> |
| 638 | |
| 639 | <li><b>Indexing a complex number</b>: a complex number can be indexed |
| 640 | either by a cdata number or a Lua number with the values 0 or 1, or by |
| 641 | the strings <tt>"re"</tt> or <tt>"im"</tt>. A read access loads the |
| 642 | real part (<tt>[0]</tt>, <tt>.re</tt>) or the imaginary part |
| 643 | (<tt>[1]</tt>, <tt>.im</tt>) part of a complex number and |
| 644 | <a href="#convert_tolua">converts it to a Lua number</a>. The |
| 645 | sub-parts of a complex number are immutable — assigning to an |
| 646 | index of a complex number raises an error. Accessing out-of-bound |
| 647 | indexes returns unspecified results, but is guaranteed not to trigger |
| 648 | memory access violations.</li> |
| 649 | |
| 650 | <li><b>Indexing a vector</b>: a vector is treated like an array for |
| 651 | indexing purposes, except the vector elements are immutable — |
| 652 | assigning to an index of a vector raises an error.</li> |
| 653 | |
| 654 | </ul> |
| 655 | <p> |
| 656 | A ctype object can be indexed with a string key, too. The only |
| 657 | predefined operation is reading scoped constants of |
| 658 | <tt>struct</tt>/<tt>union</tt> types. All other accesses defer |
| 659 | to the corresponding metamethods or index tables (if any). |
| 660 | </p> |
| 661 | <p> |
| 662 | Note: since there's (deliberately) no address-of operator, a cdata |
| 663 | object holding a value type is effectively immutable after |
| 664 | initialization. The JIT compiler benefits from this fact when applying |
| 665 | certain optimizations. |
| 666 | </p> |
| 667 | <p> |
| 668 | As a consequence, the <em>elements</em> of complex numbers and |
| 669 | vectors are immutable. But the elements of an aggregate holding these |
| 670 | types <em>may</em> be modified, of course. I.e. you cannot assign to |
| 671 | <tt>foo.c.im</tt>, but you can assign a (newly created) complex number |
| 672 | to <tt>foo.c</tt>. |
| 673 | </p> |
| 674 | <p> |
| 675 | The JIT compiler implements strict aliasing rules: accesses to different |
| 676 | types do <b>not</b> alias, except for differences in signedness (this |
| 677 | applies even to <tt>char</tt> pointers, unlike C99). Type punning |
| 678 | through unions is explicitly detected and allowed. |
| 679 | </p> |
| 680 | |
| 681 | <h3 id="cdata_call">Calling a cdata object</h3> |
| 682 | <ul> |
| 683 | |
| 684 | <li><b>Constructor</b>: a ctype object can be called and used as a |
| 685 | <a href="ext_ffi_api.html#ffi_new">constructor</a>. This is equivalent |
| 686 | to <tt>ffi.new(ct, ...)</tt>, unless a <tt>__new</tt> metamethod is |
| 687 | defined. The <tt>__new</tt> metamethod is called with the ctype object |
| 688 | plus any other arguments passed to the constructor. Note that you have to |
| 689 | use <tt>ffi.new</tt> inside the metamethod, since calling <tt>ct(...)</tt> |
| 690 | would cause infinite recursion.</li> |
| 691 | |
| 692 | <li><b>C function call</b>: a cdata function or cdata function |
| 693 | pointer can be called. The passed arguments are |
| 694 | <a href="#convert_fromlua">converted to the C types</a> of the |
| 695 | parameters given by the function declaration. Arguments passed to the |
| 696 | variable argument part of vararg C function use |
| 697 | <a href="#convert_vararg">special conversion rules</a>. This |
| 698 | C function is called and the return value (if any) is |
| 699 | <a href="#convert_tolua">converted to a Lua object</a>.<br> |
| 700 | On Windows/x86 systems, <tt>__stdcall</tt> functions are automatically |
| 701 | detected, and a function declared as <tt>__cdecl</tt> (the default) is |
| 702 | silently fixed up after the first call.</li> |
| 703 | |
| 704 | </ul> |
| 705 | |
| 706 | <h3 id="cdata_arith">Arithmetic on cdata objects</h3> |
| 707 | <ul> |
| 708 | |
| 709 | <li><b>Pointer arithmetic</b>: a cdata pointer/array and a cdata |
| 710 | number or a Lua number can be added or subtracted. The number must be |
| 711 | on the right-hand side for a subtraction. The result is a pointer of |
| 712 | the same type with an address plus or minus the number value |
| 713 | multiplied by the element size in bytes. An error is raised if the |
| 714 | element size is undefined.</li> |
| 715 | |
| 716 | <li><b>Pointer difference</b>: two compatible cdata pointers/arrays |
| 717 | can be subtracted. The result is the difference between their |
| 718 | addresses, divided by the element size in bytes. An error is raised if |
| 719 | the element size is undefined or zero.</li> |
| 720 | |
| 721 | <li><b>64 bit integer arithmetic</b>: the standard arithmetic |
| 722 | operators (<tt>+ - * / % ^</tt> and unary |
| 723 | minus) can be applied to two cdata numbers, or a cdata number and a |
| 724 | Lua number. If one of them is an <tt>uint64_t</tt>, the other side is |
| 725 | converted to an <tt>uint64_t</tt> and an unsigned arithmetic operation |
| 726 | is performed. Otherwise, both sides are converted to an |
| 727 | <tt>int64_t</tt> and a signed arithmetic operation is performed. The |
| 728 | result is a boxed 64 bit cdata object.<br> |
| 729 | |
| 730 | If one of the operands is an <tt>enum</tt> and the other operand is a |
| 731 | string, the string is converted to the value of a matching <tt>enum</tt> |
| 732 | constant before the above conversion.<br> |
| 733 | |
| 734 | These rules ensure that 64 bit integers are "sticky". Any |
| 735 | expression involving at least one 64 bit integer operand results |
| 736 | in another one. The undefined cases for the division, modulo and power |
| 737 | operators return <tt>2LL ^ 63</tt> or |
| 738 | <tt>2ULL ^ 63</tt>.<br> |
| 739 | |
| 740 | You'll have to explicitly convert a 64 bit integer to a Lua |
| 741 | number (e.g. for regular floating-point calculations) with |
| 742 | <tt>tonumber()</tt>. But note this may incur a precision loss.</li> |
| 743 | |
| 744 | <li><b>64 bit bitwise operations</b>: the rules for 64 bit |
| 745 | arithmetic operators apply analogously.<br> |
| 746 | |
| 747 | Unlike the other <tt>bit.*</tt> operations, <tt>bit.tobit()</tt> |
| 748 | converts a cdata number via <tt>int64_t</tt> to <tt>int32_t</tt> and |
| 749 | returns a Lua number.<br> |
| 750 | |
| 751 | For <tt>bit.band()</tt>, <tt>bit.bor()</tt> and <tt>bit.bxor()</tt>, the |
| 752 | conversion to <tt>int64_t</tt> or <tt>uint64_t</tt> applies to |
| 753 | <em>all</em> arguments, if <em>any</em> argument is a cdata number.<br> |
| 754 | |
| 755 | For all other operations, only the first argument is used to determine |
| 756 | the output type. This implies that a cdata number as a shift count for |
| 757 | shifts and rotates is accepted, but that alone does <em>not</em> cause |
| 758 | a cdata number output. |
| 759 | |
| 760 | </ul> |
| 761 | |
| 762 | <h3 id="cdata_comp">Comparisons of cdata objects</h3> |
| 763 | <ul> |
| 764 | |
| 765 | <li><b>Pointer comparison</b>: two compatible cdata pointers/arrays |
| 766 | can be compared. The result is the same as an unsigned comparison of |
| 767 | their addresses. <tt>nil</tt> is treated like a <tt>NULL</tt> pointer, |
| 768 | which is compatible with any other pointer type.</li> |
| 769 | |
| 770 | <li><b>64 bit integer comparison</b>: two cdata numbers, or a |
| 771 | cdata number and a Lua number can be compared with each other. If one |
| 772 | of them is an <tt>uint64_t</tt>, the other side is converted to an |
| 773 | <tt>uint64_t</tt> and an unsigned comparison is performed. Otherwise, |
| 774 | both sides are converted to an <tt>int64_t</tt> and a signed |
| 775 | comparison is performed.<br> |
| 776 | |
| 777 | If one of the operands is an <tt>enum</tt> and the other operand is a |
| 778 | string, the string is converted to the value of a matching <tt>enum</tt> |
| 779 | constant before the above conversion.<br> |
| 780 | |
| 781 | <li><b>Comparisons for equality/inequality</b> never raise an error. |
| 782 | Even incompatible pointers can be compared for equality by address. Any |
| 783 | other incompatible comparison (also with non-cdata objects) treats the |
| 784 | two sides as unequal.</li> |
| 785 | |
| 786 | </ul> |
| 787 | |
| 788 | <h3 id="cdata_key">cdata objects as table keys</h3> |
| 789 | <p> |
| 790 | Lua tables may be indexed by cdata objects, but this doesn't provide |
| 791 | any useful semantics — <b>cdata objects are unsuitable as table |
| 792 | keys!</b> |
| 793 | </p> |
| 794 | <p> |
| 795 | A cdata object is treated like any other garbage-collected object and |
| 796 | is hashed and compared by its address for table indexing. Since |
| 797 | there's no interning for cdata value types, the same value may be |
| 798 | boxed in different cdata objects with different addresses. Thus, |
| 799 | <tt>t[1LL+1LL]</tt> and <tt>t[2LL]</tt> usually <b>do not</b> point to |
| 800 | the same hash slot, and they certainly <b>do not</b> point to the same |
| 801 | hash slot as <tt>t[2]</tt>. |
| 802 | </p> |
| 803 | <p> |
| 804 | It would seriously drive up implementation complexity and slow down |
| 805 | the common case, if one were to add extra handling for by-value |
| 806 | hashing and comparisons to Lua tables. Given the ubiquity of their use |
| 807 | inside the VM, this is not acceptable. |
| 808 | </p> |
| 809 | <p> |
| 810 | There are three viable alternatives, if you really need to use cdata |
| 811 | objects as keys: |
| 812 | </p> |
| 813 | <ul> |
| 814 | |
| 815 | <li>If you can get by with the precision of Lua numbers |
| 816 | (52 bits), then use <tt>tonumber()</tt> on a cdata number or |
| 817 | combine multiple fields of a cdata aggregate to a Lua number. Then use |
| 818 | the resulting Lua number as a key when indexing tables.<br> |
| 819 | One obvious benefit: <tt>t[tonumber(2LL)]</tt> <b>does</b> point to |
| 820 | the same slot as <tt>t[2]</tt>.</li> |
| 821 | |
| 822 | <li>Otherwise, use either <tt>tostring()</tt> on 64 bit integers |
| 823 | or complex numbers or combine multiple fields of a cdata aggregate to |
| 824 | a Lua string (e.g. with |
| 825 | <a href="ext_ffi_api.html#ffi_string"><tt>ffi.string()</tt></a>). Then |
| 826 | use the resulting Lua string as a key when indexing tables.</li> |
| 827 | |
| 828 | <li>Create your own specialized hash table implementation using the |
| 829 | C types provided by the FFI library, just like you would in |
| 830 | C code. Ultimately, this may give much better performance than the |
| 831 | other alternatives or what a generic by-value hash table could |
| 832 | possibly provide.</li> |
| 833 | |
| 834 | </ul> |
| 835 | |
| 836 | <h2 id="param">Parameterized Types</h2> |
| 837 | <p> |
| 838 | To facilitate some abstractions, the two functions |
| 839 | <a href="ext_ffi_api.html#ffi_typeof"><tt>ffi.typeof</tt></a> and |
| 840 | <a href="ext_ffi_api.html#ffi_cdef"><tt>ffi.cdef</tt></a> support |
| 841 | parameterized types in C declarations. Note: none of the other API |
| 842 | functions taking a cdecl allow this. |
| 843 | </p> |
| 844 | <p> |
| 845 | Any place you can write a <b><tt>typedef</tt> name</b>, an |
| 846 | <b>identifier</b> or a <b>number</b> in a declaration, you can write |
| 847 | <tt>$</tt> (the dollar sign) instead. These placeholders are replaced in |
| 848 | order of appearance with the arguments following the cdecl string: |
| 849 | </p> |
| 850 | <pre class="code"> |
| 851 | -- Declare a struct with a parameterized field type and name: |
| 852 | ffi.cdef([[ |
| 853 | typedef struct { $ $; } foo_t; |
| 854 | ]], type1, name1) |
| 855 | |
| 856 | -- Anonymous struct with dynamic names: |
| 857 | local bar_t = ffi.typeof("struct { int $, $; }", name1, name2) |
| 858 | -- Derived pointer type: |
| 859 | local bar_ptr_t = ffi.typeof("$ *", bar_t) |
| 860 | |
| 861 | -- Parameterized dimensions work even where a VLA won't work: |
| 862 | local matrix_t = ffi.typeof("uint8_t[$][$]", width, height) |
| 863 | </pre> |
| 864 | <p> |
| 865 | Caveat: this is <em>not</em> simple text substitution! A passed ctype or |
| 866 | cdata object is treated like the underlying type, a passed string is |
| 867 | considered an identifier and a number is considered a number. You must |
| 868 | not mix this up: e.g. passing <tt>"int"</tt> as a string doesn't work in |
| 869 | place of a type, you'd need to use <tt>ffi.typeof("int")</tt> instead. |
| 870 | </p> |
| 871 | <p> |
| 872 | The main use for parameterized types are libraries implementing abstract |
| 873 | data types |
| 874 | (<a href="https://www.freelists.org/post/luajit/ffi-type-of-pointer-to,8"><span class="ext">»</span> example</a>), |
| 875 | similar to what can be achieved with C++ template metaprogramming. |
| 876 | Another use case are derived types of anonymous structs, which avoids |
| 877 | pollution of the global struct namespace. |
| 878 | </p> |
| 879 | <p> |
| 880 | Please note that parameterized types are a nice tool and indispensable |
| 881 | for certain use cases. But you'll want to use them sparingly in regular |
| 882 | code, e.g. when all types are actually fixed. |
| 883 | </p> |
| 884 | |
| 885 | <h2 id="gc">Garbage Collection of cdata Objects</h2> |
| 886 | <p> |
| 887 | All explicitly (<tt>ffi.new()</tt>, <tt>ffi.cast()</tt> etc.) or |
| 888 | implicitly (accessors) created cdata objects are garbage collected. |
| 889 | You need to ensure to retain valid references to cdata objects |
| 890 | somewhere on a Lua stack, an upvalue or in a Lua table while they are |
| 891 | still in use. Once the last reference to a cdata object is gone, the |
| 892 | garbage collector will automatically free the memory used by it (at |
| 893 | the end of the next GC cycle). |
| 894 | </p> |
| 895 | <p> |
| 896 | Please note, that pointers themselves are cdata objects, however they |
| 897 | are <b>not</b> followed by the garbage collector. So e.g. if you |
| 898 | assign a cdata array to a pointer, you must keep the cdata object |
| 899 | holding the array alive as long as the pointer is still in use: |
| 900 | </p> |
| 901 | <pre class="code"> |
| 902 | ffi.cdef[[ |
| 903 | typedef struct { int *a; } foo_t; |
| 904 | ]] |
| 905 | |
| 906 | local s = ffi.new("foo_t", ffi.new("int[10]")) -- <span style="color:#c00000;">WRONG!</span> |
| 907 | |
| 908 | local a = ffi.new("int[10]") -- <span style="color:#00a000;">OK</span> |
| 909 | local s = ffi.new("foo_t", a) |
| 910 | -- Now do something with 's', but keep 'a' alive until you're done. |
| 911 | </pre> |
| 912 | <p> |
| 913 | Similar rules apply for Lua strings which are implicitly converted to |
| 914 | <tt>"const char *"</tt>: the string object itself must be |
| 915 | referenced somewhere or it'll be garbage collected eventually. The |
| 916 | pointer will then point to stale data, which may have already been |
| 917 | overwritten. Note that <em>string literals</em> are automatically kept |
| 918 | alive as long as the function containing it (actually its prototype) |
| 919 | is not garbage collected. |
| 920 | </p> |
| 921 | <p> |
| 922 | Objects which are passed as an argument to an external C function |
| 923 | are kept alive until the call returns. So it's generally safe to |
| 924 | create temporary cdata objects in argument lists. This is a common |
| 925 | idiom for <a href="#convert_vararg">passing specific C types to |
| 926 | vararg functions</a>. |
| 927 | </p> |
| 928 | <p> |
| 929 | Memory areas returned by C functions (e.g. from <tt>malloc()</tt>) |
| 930 | must be manually managed, of course (or use |
| 931 | <a href="ext_ffi_api.html#ffi_gc"><tt>ffi.gc()</tt></a>). Pointers to |
| 932 | cdata objects are indistinguishable from pointers returned by C |
| 933 | functions (which is one of the reasons why the GC cannot follow them). |
| 934 | </p> |
| 935 | |
| 936 | <h2 id="callback">Callbacks</h2> |
| 937 | <p> |
| 938 | The LuaJIT FFI automatically generates special callback functions |
| 939 | whenever a Lua function is converted to a C function pointer. This |
| 940 | associates the generated callback function pointer with the C type |
| 941 | of the function pointer and the Lua function object (closure). |
| 942 | </p> |
| 943 | <p> |
| 944 | This can happen implicitly due to the usual conversions, e.g. when |
| 945 | passing a Lua function to a function pointer argument. Or, you can use |
| 946 | <tt>ffi.cast()</tt> to explicitly cast a Lua function to a |
| 947 | C function pointer. |
| 948 | </p> |
| 949 | <p> |
| 950 | Currently, only certain C function types can be used as callback |
| 951 | functions. Neither C vararg functions nor functions with |
| 952 | pass-by-value aggregate argument or result types are supported. There |
| 953 | are no restrictions on the kind of Lua functions that can be called |
| 954 | from the callback — no checks for the proper number of arguments |
| 955 | are made. The return value of the Lua function will be converted to the |
| 956 | result type, and an error will be thrown for invalid conversions. |
| 957 | </p> |
| 958 | <p> |
| 959 | It's allowed to throw errors across a callback invocation, but it's not |
| 960 | advisable in general. Do this only if you know the C function, that |
| 961 | called the callback, copes with the forced stack unwinding and doesn't |
| 962 | leak resources. |
| 963 | </p> |
| 964 | <p> |
| 965 | One thing that's not allowed, is to let an FFI call into a C function |
| 966 | get JIT-compiled, which in turn calls a callback, calling into Lua again. |
| 967 | Usually this attempt is caught by the interpreter first and the |
| 968 | C function is blacklisted for compilation. |
| 969 | </p> |
| 970 | <p> |
| 971 | However, this heuristic may fail under specific circumstances: e.g. a |
| 972 | message polling function might not run Lua callbacks right away and the call |
| 973 | gets JIT-compiled. If it later happens to call back into Lua (e.g. a rarely |
| 974 | invoked error callback), you'll get a VM PANIC with the message |
| 975 | <tt>"bad callback"</tt>. Then you'll need to manually turn off |
| 976 | JIT-compilation with |
| 977 | <a href="ext_jit.html#jit_onoff_func"><tt>jit.off()</tt></a> for the |
| 978 | surrounding Lua function that invokes such a message polling function (or |
| 979 | similar). |
| 980 | </p> |
| 981 | |
| 982 | <h3 id="callback_resources">Callback resource handling</h3> |
| 983 | <p> |
| 984 | Callbacks take up resources — you can only have a limited number |
| 985 | of them at the same time (500 - 1000, depending on the |
| 986 | architecture). The associated Lua functions are anchored to prevent |
| 987 | garbage collection, too. |
| 988 | </p> |
| 989 | <p> |
| 990 | <b>Callbacks due to implicit conversions are permanent!</b> There is no |
| 991 | way to guess their lifetime, since the C side might store the |
| 992 | function pointer for later use (typical for GUI toolkits). The associated |
| 993 | resources cannot be reclaimed until termination: |
| 994 | </p> |
| 995 | <pre class="code"> |
| 996 | ffi.cdef[[ |
| 997 | typedef int (__stdcall *WNDENUMPROC)(void *hwnd, intptr_t l); |
| 998 | int EnumWindows(WNDENUMPROC func, intptr_t l); |
| 999 | ]] |
| 1000 | |
| 1001 | -- Implicit conversion to a callback via function pointer argument. |
| 1002 | local count = 0 |
| 1003 | ffi.C.EnumWindows(function(hwnd, l) |
| 1004 | count = count + 1 |
| 1005 | return true |
| 1006 | end, 0) |
| 1007 | -- The callback is permanent and its resources cannot be reclaimed! |
| 1008 | -- Ok, so this may not be a problem, if you do this only once. |
| 1009 | </pre> |
| 1010 | <p> |
| 1011 | Note: this example shows that you <em>must</em> properly declare |
| 1012 | <tt>__stdcall</tt> callbacks on Windows/x86 systems. The calling |
| 1013 | convention cannot be automatically detected, unlike for |
| 1014 | <tt>__stdcall</tt> calls <em>to</em> Windows functions. |
| 1015 | </p> |
| 1016 | <p> |
| 1017 | For some use cases, it's necessary to free up the resources or to |
| 1018 | dynamically redirect callbacks. Use an explicit cast to a |
| 1019 | C function pointer and keep the resulting cdata object. Then use |
| 1020 | the <a href="ext_ffi_api.html#callback_free"><tt>cb:free()</tt></a> |
| 1021 | or <a href="ext_ffi_api.html#callback_set"><tt>cb:set()</tt></a> methods |
| 1022 | on the cdata object: |
| 1023 | </p> |
| 1024 | <pre class="code"> |
| 1025 | -- Explicitly convert to a callback via cast. |
| 1026 | local count = 0 |
| 1027 | local cb = ffi.cast("WNDENUMPROC", function(hwnd, l) |
| 1028 | count = count + 1 |
| 1029 | return true |
| 1030 | end) |
| 1031 | |
| 1032 | -- Pass it to a C function. |
| 1033 | ffi.C.EnumWindows(cb, 0) |
| 1034 | -- EnumWindows doesn't need the callback after it returns, so free it. |
| 1035 | |
| 1036 | cb:free() |
| 1037 | -- The callback function pointer is no longer valid and its resources |
| 1038 | -- will be reclaimed. The created Lua closure will be garbage collected. |
| 1039 | </pre> |
| 1040 | |
| 1041 | <h3 id="callback_performance">Callback performance</h3> |
| 1042 | <p> |
| 1043 | <b>Callbacks are slow!</b> First, the C to Lua transition itself |
| 1044 | has an unavoidable cost, similar to a <tt>lua_call()</tt> or |
| 1045 | <tt>lua_pcall()</tt>. Argument and result marshalling add to that cost. |
| 1046 | And finally, neither the C compiler nor LuaJIT can inline or |
| 1047 | optimize across the language barrier and hoist repeated computations out |
| 1048 | of a callback function. |
| 1049 | </p> |
| 1050 | <p> |
| 1051 | Do not use callbacks for performance-sensitive work: e.g. consider a |
| 1052 | numerical integration routine which takes a user-defined function to |
| 1053 | integrate over. It's a bad idea to call a user-defined Lua function from |
| 1054 | C code millions of times. The callback overhead will be absolutely |
| 1055 | detrimental for performance. |
| 1056 | </p> |
| 1057 | <p> |
| 1058 | It's considerably faster to write the numerical integration routine |
| 1059 | itself in Lua — the JIT compiler will be able to inline the |
| 1060 | user-defined function and optimize it together with its calling context, |
| 1061 | with very competitive performance. |
| 1062 | </p> |
| 1063 | <p> |
| 1064 | As a general guideline: <b>use callbacks only when you must</b>, because |
| 1065 | of existing C APIs. E.g. callback performance is irrelevant for a |
| 1066 | GUI application, which waits for user input most of the time, anyway. |
| 1067 | </p> |
| 1068 | <p> |
| 1069 | For new designs <b>avoid push-style APIs</b>: a C function repeatedly |
| 1070 | calling a callback for each result. Instead, <b>use pull-style APIs</b>: |
| 1071 | call a C function repeatedly to get a new result. Calls from Lua |
| 1072 | to C via the FFI are much faster than the other way round. Most well-designed |
| 1073 | libraries already use pull-style APIs (read/write, get/put). |
| 1074 | </p> |
| 1075 | |
| 1076 | <h2 id="clib">C Library Namespaces</h2> |
| 1077 | <p> |
| 1078 | A C library namespace is a special kind of object which allows |
| 1079 | access to the symbols contained in shared libraries or the default |
| 1080 | symbol namespace. The default |
| 1081 | <a href="ext_ffi_api.html#ffi_C"><tt>ffi.C</tt></a> namespace is |
| 1082 | automatically created when the FFI library is loaded. C library |
| 1083 | namespaces for specific shared libraries may be created with the |
| 1084 | <a href="ext_ffi_api.html#ffi_load"><tt>ffi.load()</tt></a> API |
| 1085 | function. |
| 1086 | </p> |
| 1087 | <p> |
| 1088 | Indexing a C library namespace object with a symbol name (a Lua |
| 1089 | string) automatically binds it to the library. First, the symbol type |
| 1090 | is resolved — it must have been declared with |
| 1091 | <a href="ext_ffi_api.html#ffi_cdef"><tt>ffi.cdef</tt></a>. Then the |
| 1092 | symbol address is resolved by searching for the symbol name in the |
| 1093 | associated shared libraries or the default symbol namespace. Finally, |
| 1094 | the resulting binding between the symbol name, the symbol type and its |
| 1095 | address is cached. Missing symbol declarations or nonexistent symbol |
| 1096 | names cause an error. |
| 1097 | </p> |
| 1098 | <p> |
| 1099 | This is what happens on a <b>read access</b> for the different kinds of |
| 1100 | symbols: |
| 1101 | </p> |
| 1102 | <ul> |
| 1103 | |
| 1104 | <li>External functions: a cdata object with the type of the function |
| 1105 | and its address is returned.</li> |
| 1106 | |
| 1107 | <li>External variables: the symbol address is dereferenced and the |
| 1108 | loaded value is <a href="#convert_tolua">converted to a Lua object</a> |
| 1109 | and returned.</li> |
| 1110 | |
| 1111 | <li>Constant values (<tt>static const</tt> or <tt>enum</tt> |
| 1112 | constants): the constant is <a href="#convert_tolua">converted to a |
| 1113 | Lua object</a> and returned.</li> |
| 1114 | |
| 1115 | </ul> |
| 1116 | <p> |
| 1117 | This is what happens on a <b>write access</b>: |
| 1118 | </p> |
| 1119 | <ul> |
| 1120 | |
| 1121 | <li>External variables: the value to be written is |
| 1122 | <a href="#convert_fromlua">converted to the C type</a> of the |
| 1123 | variable and then stored at the symbol address.</li> |
| 1124 | |
| 1125 | <li>Writing to constant variables or to any other symbol type causes |
| 1126 | an error, like any other attempted write to a constant location.</li> |
| 1127 | |
| 1128 | </ul> |
| 1129 | <p> |
| 1130 | C library namespaces themselves are garbage collected objects. If |
| 1131 | the last reference to the namespace object is gone, the garbage |
| 1132 | collector will eventually release the shared library reference and |
| 1133 | remove all memory associated with the namespace. Since this may |
| 1134 | trigger the removal of the shared library from the memory of the |
| 1135 | running process, it's generally <em>not safe</em> to use function |
| 1136 | cdata objects obtained from a library if the namespace object may be |
| 1137 | unreferenced. |
| 1138 | </p> |
| 1139 | <p> |
| 1140 | Performance notice: the JIT compiler specializes to the identity of |
| 1141 | namespace objects and to the strings used to index it. This |
| 1142 | effectively turns function cdata objects into constants. It's not |
| 1143 | useful and actually counter-productive to explicitly cache these |
| 1144 | function objects, e.g. <tt>local strlen = ffi.C.strlen</tt>. OTOH, it |
| 1145 | <em>is</em> useful to cache the namespace itself, e.g. <tt>local C = |
| 1146 | ffi.C</tt>. |
| 1147 | </p> |
| 1148 | |
| 1149 | <h2 id="policy">No Hand-holding!</h2> |
| 1150 | <p> |
| 1151 | The FFI library has been designed as <b>a low-level library</b>. The |
| 1152 | goal is to interface with C code and C data types with a |
| 1153 | minimum of overhead. This means <b>you can do anything you can do |
| 1154 | from C</b>: access all memory, overwrite anything in memory, call |
| 1155 | machine code at any memory address and so on. |
| 1156 | </p> |
| 1157 | <p> |
| 1158 | The FFI library provides <b>no memory safety</b>, unlike regular Lua |
| 1159 | code. It will happily allow you to dereference a <tt>NULL</tt> |
| 1160 | pointer, to access arrays out of bounds or to misdeclare |
| 1161 | C functions. If you make a mistake, your application might crash, |
| 1162 | just like equivalent C code would. |
| 1163 | </p> |
| 1164 | <p> |
| 1165 | This behavior is inevitable, since the goal is to provide full |
| 1166 | interoperability with C code. Adding extra safety measures, like |
| 1167 | bounds checks, would be futile. There's no way to detect |
| 1168 | misdeclarations of C functions, since shared libraries only |
| 1169 | provide symbol names, but no type information. Likewise, there's no way |
| 1170 | to infer the valid range of indexes for a returned pointer. |
| 1171 | </p> |
| 1172 | <p> |
| 1173 | Again: the FFI library is a low-level library. This implies it needs |
| 1174 | to be used with care, but it's flexibility and performance often |
| 1175 | outweigh this concern. If you're a C or C++ developer, it'll be easy |
| 1176 | to apply your existing knowledge. OTOH, writing code for the FFI |
| 1177 | library is not for the faint of heart and probably shouldn't be the |
| 1178 | first exercise for someone with little experience in Lua, C or C++. |
| 1179 | </p> |
| 1180 | <p> |
| 1181 | As a corollary of the above, the FFI library is <b>not safe for use by |
| 1182 | untrusted Lua code</b>. If you're sandboxing untrusted Lua code, you |
| 1183 | definitely don't want to give this code access to the FFI library or |
| 1184 | to <em>any</em> cdata object (except 64 bit integers or complex |
| 1185 | numbers). Any properly engineered Lua sandbox needs to provide safety |
| 1186 | wrappers for many of the standard Lua library functions — |
| 1187 | similar wrappers need to be written for high-level operations on FFI |
| 1188 | data types, too. |
| 1189 | </p> |
| 1190 | |
| 1191 | <h2 id="status">Current Status</h2> |
| 1192 | <p> |
| 1193 | The initial release of the FFI library has some limitations and is |
| 1194 | missing some features. Most of these will be fixed in future releases. |
| 1195 | </p> |
| 1196 | <p> |
| 1197 | <a href="#clang">C language support</a> is |
| 1198 | currently incomplete: |
| 1199 | </p> |
| 1200 | <ul> |
| 1201 | <li>C declarations are not passed through a C pre-processor, |
| 1202 | yet.</li> |
| 1203 | <li>The C parser is able to evaluate most constant expressions |
| 1204 | commonly found in C header files. However, it doesn't handle the |
| 1205 | full range of C expression semantics and may fail for some |
| 1206 | obscure constructs.</li> |
| 1207 | <li><tt>static const</tt> declarations only work for integer types |
| 1208 | up to 32 bits. Neither declaring string constants nor |
| 1209 | floating-point constants is supported.</li> |
| 1210 | <li>Packed <tt>struct</tt> bitfields that cross container boundaries |
| 1211 | are not implemented.</li> |
| 1212 | <li>Native vector types may be defined with the GCC <tt>mode</tt> or |
| 1213 | <tt>vector_size</tt> attribute. But no operations other than loading, |
| 1214 | storing and initializing them are supported, yet.</li> |
| 1215 | <li>The <tt>volatile</tt> type qualifier is currently ignored by |
| 1216 | compiled code.</li> |
| 1217 | <li><a href="ext_ffi_api.html#ffi_cdef"><tt>ffi.cdef</tt></a> silently |
| 1218 | ignores most re-declarations. Note: avoid re-declarations which do not |
| 1219 | conform to C99. The implementation will eventually be changed to |
| 1220 | perform strict checks.</li> |
| 1221 | </ul> |
| 1222 | <p> |
| 1223 | The JIT compiler already handles a large subset of all FFI operations. |
| 1224 | It automatically falls back to the interpreter for unimplemented |
| 1225 | operations (you can check for this with the |
| 1226 | <a href="running.html#opt_j"><tt>-jv</tt></a> command line option). |
| 1227 | The following operations are currently not compiled and may exhibit |
| 1228 | suboptimal performance, especially when used in inner loops: |
| 1229 | </p> |
| 1230 | <ul> |
| 1231 | <li>Vector operations.</li> |
| 1232 | <li>Table initializers.</li> |
| 1233 | <li>Initialization of nested <tt>struct</tt>/<tt>union</tt> types.</li> |
| 1234 | <li>Non-default initialization of VLA/VLS or large C types |
| 1235 | (> 128 bytes or > 16 array elements).</li> |
| 1236 | <li>Bitfield initializations.</li> |
| 1237 | <li>Pointer differences for element sizes that are not a power of |
| 1238 | two.</li> |
| 1239 | <li>Calls to C functions with aggregates passed or returned by |
| 1240 | value.</li> |
| 1241 | <li>Calls to ctype metamethods which are not plain functions.</li> |
| 1242 | <li>ctype <tt>__newindex</tt> tables and non-string lookups in ctype |
| 1243 | <tt>__index</tt> tables.</li> |
| 1244 | <li><tt>tostring()</tt> for cdata types.</li> |
| 1245 | <li>Calls to <tt>ffi.cdef()</tt>, <tt>ffi.load()</tt> and |
| 1246 | <tt>ffi.metatype()</tt>.</li> |
| 1247 | </ul> |
| 1248 | <p> |
| 1249 | Other missing features: |
| 1250 | </p> |
| 1251 | <ul> |
| 1252 | <li>Arithmetic for <tt>complex</tt> numbers.</li> |
| 1253 | <li>Passing structs by value to vararg C functions.</li> |
| 1254 | <li><a href="extensions.html#exceptions">C++ exception interoperability</a> |
| 1255 | does not extend to C functions called via the FFI, if the call is |
| 1256 | compiled.</li> |
| 1257 | </ul> |
| 1258 | <br class="flush"> |
| 1259 | </div> |
| 1260 | <div id="foot"> |
| 1261 | <hr class="hide"> |
| 1262 | Copyright © 2005-2025 |
| 1263 | <span class="noprint"> |
| 1264 | · |
| 1265 | <a href="contact.html">Contact</a> |
| 1266 | </span> |
| 1267 | </div> |
| 1268 | </body> |
| 1269 | </html> |