ext_ffi_semantics.html 52 KB

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