ext_ffi_tutorial.html 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>FFI Tutorial</title>
  5. <meta charset="utf-8">
  6. <meta name="Copyright" content="Copyright (C) 2005-2022">
  7. <meta name="Language" content="en">
  8. <link rel="stylesheet" type="text/css" href="bluequad.css" media="screen">
  9. <link rel="stylesheet" type="text/css" href="bluequad-print.css" media="print">
  10. <style type="text/css">
  11. table.idiomtable { font-size: 90%; line-height: 1.2; }
  12. table.idiomtable tt { font-size: 100%; }
  13. table.idiomtable td { vertical-align: top; }
  14. tr.idiomhead td { font-weight: bold; }
  15. td.idiomlua b { font-weight: normal; color: #2142bf; }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="site">
  20. <a href="https://luajit.org"><span>Lua<span id="logo">JIT</span></span></a>
  21. </div>
  22. <div id="head">
  23. <h1>FFI Tutorial</h1>
  24. </div>
  25. <div id="nav">
  26. <ul><li>
  27. <a href="luajit.html">LuaJIT</a>
  28. <ul><li>
  29. <a href="https://luajit.org/download.html">Download <span class="ext">&raquo;</span></a>
  30. </li><li>
  31. <a href="install.html">Installation</a>
  32. </li><li>
  33. <a href="running.html">Running</a>
  34. </li></ul>
  35. </li><li>
  36. <a href="extensions.html">Extensions</a>
  37. <ul><li>
  38. <a href="ext_ffi.html">FFI Library</a>
  39. <ul><li>
  40. <a class="current" href="ext_ffi_tutorial.html">FFI Tutorial</a>
  41. </li><li>
  42. <a href="ext_ffi_api.html">ffi.* API</a>
  43. </li><li>
  44. <a href="ext_ffi_semantics.html">FFI Semantics</a>
  45. </li></ul>
  46. </li><li>
  47. <a href="ext_buffer.html">String Buffers</a>
  48. </li><li>
  49. <a href="ext_jit.html">jit.* Library</a>
  50. </li><li>
  51. <a href="ext_c_api.html">Lua/C API</a>
  52. </li><li>
  53. <a href="ext_profiler.html">Profiler</a>
  54. </li></ul>
  55. </li><li>
  56. <a href="status.html">Status</a>
  57. </li><li>
  58. <a href="faq.html">FAQ</a>
  59. </li><li>
  60. <a href="http://wiki.luajit.org/">Wiki <span class="ext">&raquo;</span></a>
  61. </li><li>
  62. <a href="https://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 is intended to give you an overview of the features of the FFI
  68. library by presenting a few use cases and guidelines.
  69. </p>
  70. <p>
  71. This page makes no attempt to explain all of the FFI library, though.
  72. You'll want to have a look at the <a href="ext_ffi_api.html">ffi.* API
  73. function reference</a> and the <a href="ext_ffi_semantics.html">FFI
  74. semantics</a> to learn more.
  75. </p>
  76. <h2 id="load">Loading the FFI Library</h2>
  77. <p>
  78. The FFI library is built into LuaJIT by default, but it's not loaded
  79. and initialized by default. The suggested way to use the FFI library
  80. is to add the following to the start of every Lua file that needs one
  81. of its functions:
  82. </p>
  83. <pre class="code">
  84. local ffi = require("ffi")
  85. </pre>
  86. <p>
  87. Please note, this doesn't define an <tt>ffi</tt> variable in the table
  88. of globals &mdash; you really need to use the local variable. The
  89. <tt>require</tt> function ensures the library is only loaded once.
  90. </p>
  91. <p style="font-size: 8pt;">
  92. Note: If you want to experiment with the FFI from the interactive prompt
  93. of the command line executable, omit the <tt>local</tt>, as it doesn't
  94. preserve local variables across lines.
  95. </p>
  96. <h2 id="sleep">Accessing Standard System Functions</h2>
  97. <p>
  98. The following code explains how to access standard system functions.
  99. We slowly print two lines of dots by sleeping for 10&nbsp;milliseconds
  100. after each dot:
  101. </p>
  102. <pre class="code mark">
  103. <span class="codemark">&nbsp;
  104. &#9312;
  105. &#9313;
  106. &#9314;
  107. &#9315;
  108. &#9316;
  109. &#9317;</span>local ffi = require("ffi")
  110. ffi.cdef[[
  111. <span style="color:#00a000;">void Sleep(int ms);
  112. int poll(struct pollfd *fds, unsigned long nfds, int timeout);</span>
  113. ]]
  114. local sleep
  115. if ffi.os == "Windows" then
  116. function sleep(s)
  117. ffi.C.Sleep(s*1000)
  118. end
  119. else
  120. function sleep(s)
  121. ffi.C.poll(nil, 0, s*1000)
  122. end
  123. end
  124. for i=1,160 do
  125. io.write("."); io.flush()
  126. sleep(0.01)
  127. end
  128. io.write("\n")
  129. </pre>
  130. <p>
  131. Here's the step-by-step explanation:
  132. </p>
  133. <p>
  134. <span class="mark">&#9312;</span> This defines the
  135. C&nbsp;library functions we're going to use. The part inside the
  136. double-brackets (in green) is just standard C&nbsp;syntax. You can
  137. usually get this info from the C&nbsp;header files or the
  138. documentation provided by each C&nbsp;library or C&nbsp;compiler.
  139. </p>
  140. <p>
  141. <span class="mark">&#9313;</span> The difficulty we're
  142. facing here, is that there are different standards to choose from.
  143. Windows has a simple <tt>Sleep()</tt> function. On other systems there
  144. are a variety of functions available to achieve sub-second sleeps, but
  145. with no clear consensus. Thankfully <tt>poll()</tt> can be used for
  146. this task, too, and it's present on most non-Windows systems. The
  147. check for <tt>ffi.os</tt> makes sure we use the Windows-specific
  148. function only on Windows systems.
  149. </p>
  150. <p>
  151. <span class="mark">&#9314;</span> Here we're wrapping the
  152. call to the C&nbsp;function in a Lua function. This isn't strictly
  153. necessary, but it's helpful to deal with system-specific issues only
  154. in one part of the code. The way we're wrapping it ensures the check
  155. for the OS is only done during initialization and not for every call.
  156. </p>
  157. <p>
  158. <span class="mark">&#9315;</span> A more subtle point is
  159. that we defined our <tt>sleep()</tt> function (for the sake of this
  160. example) as taking the number of seconds, but accepting fractional
  161. seconds. Multiplying this by 1000 gets us milliseconds, but that still
  162. leaves it a Lua number, which is a floating-point value. Alas, the
  163. <tt>Sleep()</tt> function only accepts an integer value. Luckily for
  164. us, the FFI library automatically performs the conversion when calling
  165. the function (truncating the FP value towards zero, like in C).
  166. </p>
  167. <p style="font-size: 8pt;">
  168. Some readers will notice that <tt>Sleep()</tt> is part of
  169. <tt>KERNEL32.DLL</tt> and is also a <tt>stdcall</tt> function. So how
  170. can this possibly work? The FFI library provides the <tt>ffi.C</tt>
  171. default C&nbsp;library namespace, which allows calling functions from
  172. the default set of libraries, like a C&nbsp;compiler would. Also, the
  173. FFI library automatically detects <tt>stdcall</tt> functions, so you
  174. don't need to declare them as such.
  175. </p>
  176. <p>
  177. <span class="mark">&#9316;</span> The <tt>poll()</tt>
  178. function takes a couple more arguments we're not going to use. You can
  179. simply use <tt>nil</tt> to pass a <tt>NULL</tt> pointer and <tt>0</tt>
  180. for the <tt>nfds</tt> parameter. Please note, that the
  181. number&nbsp;<tt>0</tt> <em>does not convert to a pointer value</em>,
  182. unlike in C++. You really have to pass pointers to pointer arguments
  183. and numbers to number arguments.
  184. </p>
  185. <p style="font-size: 8pt;">
  186. The page on <a href="ext_ffi_semantics.html">FFI semantics</a> has all
  187. of the gory details about
  188. <a href="ext_ffi_semantics.html#convert">conversions between Lua
  189. objects and C&nbsp;types</a>. For the most part you don't have to deal
  190. with this, as it's performed automatically and it's carefully designed
  191. to bridge the semantic differences between Lua and C.
  192. </p>
  193. <p>
  194. <span class="mark">&#9317;</span> Now that we have defined
  195. our own <tt>sleep()</tt> function, we can just call it from plain Lua
  196. code. That wasn't so bad, huh? Turning these boring animated dots into
  197. a fascinating best-selling game is left as an exercise for the reader.
  198. :-)
  199. </p>
  200. <h2 id="zlib">Accessing the zlib Compression Library</h2>
  201. <p>
  202. The following code shows how to access the <a
  203. href="https://zlib.net/"><span class="ext">&raquo;</span>&nbsp;zlib</a> compression library from Lua code.
  204. We'll define two convenience wrapper functions that take a string and
  205. compress or uncompress it to another string:
  206. </p>
  207. <pre class="code mark">
  208. <span class="codemark">&nbsp;
  209. &#9312;
  210. &#9313;
  211. &#9314;
  212. &#9315;
  213. &#9316;
  214. &#9317;
  215. &#9318;</span>local ffi = require("ffi")
  216. ffi.cdef[[
  217. <span style="color:#00a000;">unsigned long compressBound(unsigned long sourceLen);
  218. int compress2(uint8_t *dest, unsigned long *destLen,
  219. const uint8_t *source, unsigned long sourceLen, int level);
  220. int uncompress(uint8_t *dest, unsigned long *destLen,
  221. const uint8_t *source, unsigned long sourceLen);</span>
  222. ]]
  223. local zlib = ffi.load(ffi.os == "Windows" and "zlib1" or "z")
  224. local function compress(txt)
  225. local n = zlib.compressBound(#txt)
  226. local buf = ffi.new("uint8_t[?]", n)
  227. local buflen = ffi.new("unsigned long[1]", n)
  228. local res = zlib.compress2(buf, buflen, txt, #txt, 9)
  229. assert(res == 0)
  230. return ffi.string(buf, buflen[0])
  231. end
  232. local function uncompress(comp, n)
  233. local buf = ffi.new("uint8_t[?]", n)
  234. local buflen = ffi.new("unsigned long[1]", n)
  235. local res = zlib.uncompress(buf, buflen, comp, #comp)
  236. assert(res == 0)
  237. return ffi.string(buf, buflen[0])
  238. end
  239. -- Simple test code.
  240. local txt = string.rep("abcd", 1000)
  241. print("Uncompressed size: ", #txt)
  242. local c = compress(txt)
  243. print("Compressed size: ", #c)
  244. local txt2 = uncompress(c, #txt)
  245. assert(txt2 == txt)
  246. </pre>
  247. <p>
  248. Here's the step-by-step explanation:
  249. </p>
  250. <p>
  251. <span class="mark">&#9312;</span> This defines some of the
  252. C&nbsp;functions provided by zlib. For the sake of this example, some
  253. type indirections have been reduced and it uses the predefined
  254. fixed-size integer types, while still adhering to the zlib API/ABI.
  255. </p>
  256. <p>
  257. <span class="mark">&#9313;</span> This loads the zlib shared
  258. library. On POSIX systems, it's named <tt>libz.so</tt> and usually
  259. comes pre-installed. Since <tt>ffi.load()</tt> automatically adds any
  260. missing standard prefixes/suffixes, we can simply load the
  261. <tt>"z"</tt> library. On Windows it's named <tt>zlib1.dll</tt> and
  262. you'll have to download it first from the
  263. <a href="https://zlib.net/"><span class="ext">&raquo;</span>&nbsp;zlib site</a>. The check for
  264. <tt>ffi.os</tt> makes sure we pass the right name to
  265. <tt>ffi.load()</tt>.
  266. </p>
  267. <p>
  268. <span class="mark">&#9314;</span> First, the maximum size of
  269. the compression buffer is obtained by calling the
  270. <tt>zlib.compressBound</tt> function with the length of the
  271. uncompressed string. The next line allocates a byte buffer of this
  272. size. The <tt>[?]</tt> in the type specification indicates a
  273. variable-length array (VLA). The actual number of elements of this
  274. array is given as the 2nd argument to <tt>ffi.new()</tt>.
  275. </p>
  276. <p>
  277. <span class="mark">&#9315;</span> This may look strange at
  278. first, but have a look at the declaration of the <tt>compress2</tt>
  279. function from zlib: the destination length is defined as a pointer!
  280. This is because you pass in the maximum buffer size and get back the
  281. actual length that was used.
  282. </p>
  283. <p>
  284. In C you'd pass in the address of a local variable
  285. (<tt>&amp;buflen</tt>). But since there's no address-of operator in
  286. Lua, we'll just pass in a one-element array. Conveniently, it can be
  287. initialized with the maximum buffer size in one step. Calling the
  288. actual <tt>zlib.compress2</tt> function is then straightforward.
  289. </p>
  290. <p>
  291. <span class="mark">&#9316;</span> We want to return the
  292. compressed data as a Lua string, so we'll use <tt>ffi.string()</tt>.
  293. It needs a pointer to the start of the data and the actual length. The
  294. length has been returned in the <tt>buflen</tt> array, so we'll just
  295. get it from there.
  296. </p>
  297. <p style="font-size: 8pt;">
  298. Note that since the function returns now, the <tt>buf</tt> and
  299. <tt>buflen</tt> variables will eventually be garbage collected. This
  300. is fine, because <tt>ffi.string()</tt> has copied the contents to a
  301. newly created (interned) Lua string. If you plan to call this function
  302. lots of times, consider reusing the buffers and/or handing back the
  303. results in buffers instead of strings. This will reduce the overhead
  304. for garbage collection and string interning.
  305. </p>
  306. <p>
  307. <span class="mark">&#9317;</span> The <tt>uncompress</tt>
  308. functions does the exact opposite of the <tt>compress</tt> function.
  309. The compressed data doesn't include the size of the original string,
  310. so this needs to be passed in. Otherwise, no surprises here.
  311. </p>
  312. <p>
  313. <span class="mark">&#9318;</span> The code, that makes use
  314. of the functions we just defined, is just plain Lua code. It doesn't
  315. need to know anything about the LuaJIT FFI &mdash; the convenience
  316. wrapper functions completely hide it.
  317. </p>
  318. <p>
  319. One major advantage of the LuaJIT FFI is that you are now able to
  320. write those wrappers <em>in Lua</em>. And at a fraction of the time it
  321. would cost you to create an extra C&nbsp;module using the Lua/C API.
  322. Many of the simpler C&nbsp;functions can probably be used directly
  323. from your Lua code, without any wrappers.
  324. </p>
  325. <p style="font-size: 8pt;">
  326. Side note: the zlib API uses the <tt>long</tt> type for passing
  327. lengths and sizes around. But all those zlib functions actually only
  328. deal with 32&nbsp;bit values. This is an unfortunate choice for a
  329. public API, but may be explained by zlib's history &mdash; we'll just
  330. have to deal with it.
  331. </p>
  332. <p style="font-size: 8pt;">
  333. First, you should know that a <tt>long</tt> is a 64&nbsp;bit type e.g.
  334. on POSIX/x64 systems, but a 32&nbsp;bit type on Windows/x64 and on
  335. 32&nbsp;bit systems. Thus a <tt>long</tt> result can be either a plain
  336. Lua number or a boxed 64&nbsp;bit integer cdata object, depending on
  337. the target system.
  338. </p>
  339. <p style="font-size: 8pt;">
  340. Ok, so the <tt>ffi.*</tt> functions generally accept cdata objects
  341. wherever you'd want to use a number. That's why we get a away with
  342. passing <tt>n</tt> to <tt>ffi.string()</tt> above. But other Lua
  343. library functions or modules don't know how to deal with this. So for
  344. maximum portability, one needs to use <tt>tonumber()</tt> on returned
  345. <tt>long</tt> results before passing them on. Otherwise the
  346. application might work on some systems, but would fail in a POSIX/x64
  347. environment.
  348. </p>
  349. <h2 id="metatype">Defining Metamethods for a C&nbsp;Type</h2>
  350. <p>
  351. The following code explains how to define metamethods for a C type.
  352. We define a simple point type and add some operations to it:
  353. </p>
  354. <pre class="code mark">
  355. <span class="codemark">&nbsp;
  356. &#9312;
  357. &#9313;
  358. &#9314;
  359. &#9315;
  360. &#9316;
  361. &#9317;</span>local ffi = require("ffi")
  362. ffi.cdef[[
  363. <span style="color:#00a000;">typedef struct { double x, y; } point_t;</span>
  364. ]]
  365. local point
  366. local mt = {
  367. __add = function(a, b) return point(a.x+b.x, a.y+b.y) end,
  368. __len = function(a) return math.sqrt(a.x*a.x + a.y*a.y) end,
  369. __index = {
  370. area = function(a) return a.x*a.x + a.y*a.y end,
  371. },
  372. }
  373. point = ffi.metatype("point_t", mt)
  374. local a = point(3, 4)
  375. print(a.x, a.y) --> 3 4
  376. print(#a) --> 5
  377. print(a:area()) --> 25
  378. local b = a + point(0.5, 8)
  379. print(#b) --> 12.5
  380. </pre>
  381. <p>
  382. Here's the step-by-step explanation:
  383. </p>
  384. <p>
  385. <span class="mark">&#9312;</span> This defines the C&nbsp;type for a
  386. two-dimensional point object.
  387. </p>
  388. <p>
  389. <span class="mark">&#9313;</span> We have to declare the variable
  390. holding the point constructor first, because it's used inside of a
  391. metamethod.
  392. </p>
  393. <p>
  394. <span class="mark">&#9314;</span> Let's define an <tt>__add</tt>
  395. metamethod which adds the coordinates of two points and creates a new
  396. point object. For simplicity, this function assumes that both arguments
  397. are points. But it could be any mix of objects, if at least one operand
  398. is of the required type (e.g. adding a point plus a number or vice
  399. versa). Our <tt>__len</tt> metamethod returns the distance of a point to
  400. the origin.
  401. </p>
  402. <p>
  403. <span class="mark">&#9315;</span> If we run out of operators, we can
  404. define named methods, too. Here, the <tt>__index</tt> table defines an
  405. <tt>area</tt> function. For custom indexing needs, one might want to
  406. define <tt>__index</tt> and <tt>__newindex</tt> <em>functions</em> instead.
  407. </p>
  408. <p>
  409. <span class="mark">&#9316;</span> This associates the metamethods with
  410. our C&nbsp;type. This only needs to be done once. For convenience, a
  411. constructor is returned by
  412. <a href="ext_ffi_api.html#ffi_metatype"><tt>ffi.metatype()</tt></a>.
  413. We're not required to use it, though. The original C&nbsp;type can still
  414. be used e.g. to create an array of points. The metamethods automatically
  415. apply to any and all uses of this type.
  416. </p>
  417. <p>
  418. Please note, that the association with a metatable is permanent and
  419. <b>the metatable must not be modified afterwards!</b> Ditto for the
  420. <tt>__index</tt> table.
  421. </p>
  422. <p>
  423. <span class="mark">&#9317;</span> Here are some simple usage examples
  424. for the point type and their expected results. The predefined
  425. operations (such as <tt>a.x</tt>) can be freely mixed with the newly
  426. defined metamethods. Note that <tt>area</tt> is a method and must be
  427. called with the Lua syntax for methods: <tt>a:area()</tt>, not
  428. <tt>a.area()</tt>.
  429. </p>
  430. <p>
  431. The C&nbsp;type metamethod mechanism is most useful when used in
  432. conjunction with C&nbsp;libraries that are written in an object-oriented
  433. style. Creators return a pointer to a new instance, and methods take an
  434. instance pointer as the first argument. Sometimes you can just point
  435. <tt>__index</tt> to the library namespace and <tt>__gc</tt> to the
  436. destructor and you're done. But often enough you'll want to add
  437. convenience wrappers, e.g. to return actual Lua strings or when
  438. returning multiple values.
  439. </p>
  440. <p>
  441. Some C libraries only declare instance pointers as an opaque
  442. <tt>void&nbsp;*</tt> type. In this case you can use a fake type for all
  443. declarations, e.g. a pointer to a named (incomplete) struct will do:
  444. <tt>typedef struct foo_type *foo_handle</tt>. The C&nbsp;side doesn't
  445. know what you declare with the LuaJIT FFI, but as long as the underlying
  446. types are compatible, everything still works.
  447. </p>
  448. <h2 id="idioms">Translating C&nbsp;Idioms</h2>
  449. <p>
  450. Here's a list of common C&nbsp;idioms and their translation to the
  451. LuaJIT FFI:
  452. </p>
  453. <table class="idiomtable">
  454. <tr class="idiomhead">
  455. <td class="idiomdesc">Idiom</td>
  456. <td class="idiomc">C&nbsp;code</td>
  457. <td class="idiomlua">Lua code</td>
  458. </tr>
  459. <tr class="odd separate">
  460. <td class="idiomdesc">Pointer dereference<br><tt>int *p;</tt></td><td class="idiomc"><tt>x = *p;<br>*p = y;</tt></td><td class="idiomlua"><tt>x = <b>p[0]</b><br><b>p[0]</b> = y</tt></td></tr>
  461. <tr class="even">
  462. <td class="idiomdesc">Pointer indexing<br><tt>int i, *p;</tt></td><td class="idiomc"><tt>x = p[i];<br>p[i+1] = y;</tt></td><td class="idiomlua"><tt>x = p[i]<br>p[i+1] = y</tt></td></tr>
  463. <tr class="odd">
  464. <td class="idiomdesc">Array indexing<br><tt>int i, a[];</tt></td><td class="idiomc"><tt>x = a[i];<br>a[i+1] = y;</tt></td><td class="idiomlua"><tt>x = a[i]<br>a[i+1] = y</tt></td></tr>
  465. <tr class="even separate">
  466. <td class="idiomdesc"><tt>struct</tt>/<tt>union</tt> dereference<br><tt>struct foo s;</tt></td><td class="idiomc"><tt>x = s.field;<br>s.field = y;</tt></td><td class="idiomlua"><tt>x = s.field<br>s.field = y</tt></td></tr>
  467. <tr class="odd">
  468. <td class="idiomdesc"><tt>struct</tt>/<tt>union</tt> pointer deref.<br><tt>struct foo *sp;</tt></td><td class="idiomc"><tt>x = sp->field;<br>sp->field = y;</tt></td><td class="idiomlua"><tt>x = <b>s.field</b><br><b>s.field</b> = y</tt></td></tr>
  469. <tr class="even separate">
  470. <td class="idiomdesc">Pointer arithmetic<br><tt>int i, *p;</tt></td><td class="idiomc"><tt>x = p + i;<br>y = p - i;</tt></td><td class="idiomlua"><tt>x = p + i<br>y = p - i</tt></td></tr>
  471. <tr class="odd">
  472. <td class="idiomdesc">Pointer difference<br><tt>int *p1, *p2;</tt></td><td class="idiomc"><tt>x = p1 - p2;</tt></td><td class="idiomlua"><tt>x = p1 - p2</tt></td></tr>
  473. <tr class="even">
  474. <td class="idiomdesc">Array element pointer<br><tt>int i, a[];</tt></td><td class="idiomc"><tt>x = &amp;a[i];</tt></td><td class="idiomlua"><tt>x = <b>a+i</b></tt></td></tr>
  475. <tr class="odd">
  476. <td class="idiomdesc">Cast pointer to address<br><tt>int *p;</tt></td><td class="idiomc"><tt>x = (intptr_t)p;</tt></td><td class="idiomlua"><tt>x = <b>tonumber(<br>&nbsp;ffi.cast("intptr_t",<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;p))</b></tt></td></tr>
  477. <tr class="even separate">
  478. <td class="idiomdesc">Functions with outargs<br><tt>void foo(int *inoutlen);</tt></td><td class="idiomc"><tt>int len = x;<br>foo(&amp;len);<br>y = len;</tt></td><td class="idiomlua"><tt><b>local len =<br>&nbsp;&nbsp;ffi.new("int[1]", x)<br>foo(len)<br>y = len[0]</b></tt></td></tr>
  479. <tr class="odd">
  480. <td class="idiomdesc"><a href="ext_ffi_semantics.html#convert_vararg">Vararg conversions</a><br><tt>int printf(char *fmt, ...);</tt></td><td class="idiomc"><tt>printf("%g", 1.0);<br>printf("%d", 1);<br>&nbsp;</tt></td><td class="idiomlua"><tt>printf("%g", 1);<br>printf("%d",<br>&nbsp;&nbsp;<b>ffi.new("int", 1)</b>)</tt></td></tr>
  481. </table>
  482. <h2 id="cache">To Cache or Not to Cache</h2>
  483. <p>
  484. It's a common Lua idiom to cache library functions in local variables
  485. or upvalues, e.g.:
  486. </p>
  487. <pre class="code">
  488. local byte, char = string.byte, string.char
  489. local function foo(x)
  490. return char(byte(x)+1)
  491. end
  492. </pre>
  493. <p>
  494. This replaces several hash-table lookups with a (faster) direct use of
  495. a local or an upvalue. This is less important with LuaJIT, since the
  496. JIT compiler optimizes hash-table lookups a lot and is even able to
  497. hoist most of them out of the inner loops. It can't eliminate
  498. <em>all</em> of them, though, and it saves some typing for often-used
  499. functions. So there's still a place for this, even with LuaJIT.
  500. </p>
  501. <p>
  502. The situation is a bit different with C&nbsp;function calls via the
  503. FFI library. The JIT compiler has special logic to eliminate <em>all
  504. of the lookup overhead</em> for functions resolved from a
  505. <a href="ext_ffi_semantics.html#clib">C&nbsp;library namespace</a>!
  506. Thus it's not helpful and actually counter-productive to cache
  507. individual C&nbsp;functions like this:
  508. </p>
  509. <pre class="code">
  510. local <b>funca</b>, <b>funcb</b> = ffi.C.funca, ffi.C.funcb -- <span style="color:#c00000;">Not helpful!</span>
  511. local function foo(x, n)
  512. for i=1,n do <b>funcb</b>(<b>funca</b>(x, i), 1) end
  513. end
  514. </pre>
  515. <p>
  516. This turns them into indirect calls and generates bigger and slower
  517. machine code. Instead, you'll want to cache the namespace itself and
  518. rely on the JIT compiler to eliminate the lookups:
  519. </p>
  520. <pre class="code">
  521. local <b>C</b> = ffi.C -- <span style="color:#00a000;">Instead use this!</span>
  522. local function foo(x, n)
  523. for i=1,n do <b>C.funcb</b>(<b>C.funca</b>(x, i), 1) end
  524. end
  525. </pre>
  526. <p>
  527. This generates both shorter and faster code. So <b>don't cache
  528. C&nbsp;functions</b>, but <b>do</b> cache namespaces! Most often the
  529. namespace is already in a local variable at an outer scope, e.g. from
  530. <tt>local&nbsp;lib&nbsp;=&nbsp;ffi.load(...)</tt>. Note that copying
  531. it to a local variable in the function scope is unnecessary.
  532. </p>
  533. <br class="flush">
  534. </div>
  535. <div id="foot">
  536. <hr class="hide">
  537. Copyright &copy; 2005-2022
  538. <span class="noprint">
  539. &middot;
  540. <a href="contact.html">Contact</a>
  541. </span>
  542. </div>
  543. </body>
  544. </html>