ext_ffi_tutorial.html 18 KB

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