ext_ffi_semantics.html 53 KB

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