ext_ffi_semantics.html 52 KB

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