ext_ffi.html 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>FFI Library</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. </head>
  11. <body>
  12. <div id="site">
  13. <a href="https://luajit.org"><span>Lua<span id="logo">JIT</span></span></a>
  14. </div>
  15. <div id="head">
  16. <h1>FFI Library</h1>
  17. </div>
  18. <div id="nav">
  19. <ul><li>
  20. <a href="luajit.html">LuaJIT</a>
  21. <ul><li>
  22. <a href="https://luajit.org/download.html">Download <span class="ext">&raquo;</span></a>
  23. </li><li>
  24. <a href="install.html">Installation</a>
  25. </li><li>
  26. <a href="running.html">Running</a>
  27. </li></ul>
  28. </li><li>
  29. <a href="extensions.html">Extensions</a>
  30. <ul><li>
  31. <a class="current" href="ext_ffi.html">FFI Library</a>
  32. <ul><li>
  33. <a href="ext_ffi_tutorial.html">FFI Tutorial</a>
  34. </li><li>
  35. <a href="ext_ffi_api.html">ffi.* API</a>
  36. </li><li>
  37. <a href="ext_ffi_semantics.html">FFI Semantics</a>
  38. </li></ul>
  39. </li><li>
  40. <a href="ext_buffer.html">String Buffers</a>
  41. </li><li>
  42. <a href="ext_jit.html">jit.* Library</a>
  43. </li><li>
  44. <a href="ext_c_api.html">Lua/C API</a>
  45. </li><li>
  46. <a href="ext_profiler.html">Profiler</a>
  47. </li></ul>
  48. </li><li>
  49. <a href="status.html">Status</a>
  50. </li><li>
  51. <a href="faq.html">FAQ</a>
  52. </li><li>
  53. <a href="http://wiki.luajit.org/">Wiki <span class="ext">&raquo;</span></a>
  54. </li><li>
  55. <a href="https://luajit.org/list.html">Mailing List <span class="ext">&raquo;</span></a>
  56. </li></ul>
  57. </div>
  58. <div id="main">
  59. <p>
  60. The FFI library allows <b>calling external C&nbsp;functions</b> and
  61. <b>using C&nbsp;data structures</b> from pure Lua code.
  62. </p>
  63. <p>
  64. The FFI library largely obviates the need to write tedious manual
  65. Lua/C bindings in C. No need to learn a separate binding language
  66. &mdash; <b>it parses plain C&nbsp;declarations!</b> These can be
  67. cut-n-pasted from C&nbsp;header files or reference manuals. It's up to
  68. the task of binding large libraries without the need for dealing with
  69. fragile binding generators.
  70. </p>
  71. <p>
  72. The FFI library is tightly integrated into LuaJIT (it's not available
  73. as a separate module). The code generated by the JIT-compiler for
  74. accesses to C&nbsp;data structures from Lua code is on par with the
  75. code a C&nbsp;compiler would generate. Calls to C&nbsp;functions can
  76. be inlined in JIT-compiled code, unlike calls to functions bound via
  77. the classic Lua/C API.
  78. </p>
  79. <p>
  80. This page gives a short introduction to the usage of the FFI library.
  81. <em>Please use the FFI sub-topics in the navigation bar to learn more.</em>
  82. </p>
  83. <h2 id="call">Motivating Example: Calling External C Functions</h2>
  84. <p>
  85. It's really easy to call an external C&nbsp;library function:
  86. </p>
  87. <pre class="code mark">
  88. <span class="codemark">&#9312;
  89. &#9313;
  90. &#9314;</span>local ffi = require("ffi")
  91. ffi.cdef[[
  92. <span style="color:#00a000;">int printf(const char *fmt, ...);</span>
  93. ]]
  94. ffi.C.printf("Hello %s!", "world")
  95. </pre>
  96. <p>
  97. So, let's pick that apart:
  98. </p>
  99. <p>
  100. <span class="mark">&#9312;</span> Load the FFI library.
  101. </p>
  102. <p>
  103. <span class="mark">&#9313;</span> Add a C&nbsp;declaration
  104. for the function. The part inside the double-brackets (in green) is
  105. just standard C&nbsp;syntax.
  106. </p>
  107. <p>
  108. <span class="mark">&#9314;</span> Call the named
  109. C&nbsp;function &mdash; Yes, it's that simple!
  110. </p>
  111. <p style="font-size: 8pt;">
  112. Actually, what goes on behind the scenes is far from simple: <span
  113. style="color:#4040c0;">&#9314;</span> makes use of the standard
  114. C&nbsp;library namespace <tt>ffi.C</tt>. Indexing this namespace with
  115. a symbol name (<tt>"printf"</tt>) automatically binds it to the
  116. standard C&nbsp;library. The result is a special kind of object which,
  117. when called, runs the <tt>printf</tt> function. The arguments passed
  118. to this function are automatically converted from Lua objects to the
  119. corresponding C&nbsp;types.
  120. </p>
  121. <p>
  122. Ok, so maybe the use of <tt>printf()</tt> wasn't such a spectacular
  123. example. You could have done that with <tt>io.write()</tt> and
  124. <tt>string.format()</tt>, too. But you get the idea ...
  125. </p>
  126. <p>
  127. So here's something to pop up a message box on Windows:
  128. </p>
  129. <pre class="code">
  130. local ffi = require("ffi")
  131. ffi.cdef[[
  132. <span style="color:#00a000;">int MessageBoxA(void *w, const char *txt, const char *cap, int type);</span>
  133. ]]
  134. ffi.C.MessageBoxA(nil, "Hello world!", "Test", 0)
  135. </pre>
  136. <p>
  137. Bing! Again, that was far too easy, no?
  138. </p>
  139. <p style="font-size: 8pt;">
  140. Compare this with the effort required to bind that function using the
  141. classic Lua/C API: create an extra C&nbsp;file, add a C&nbsp;function
  142. that retrieves and checks the argument types passed from Lua and calls
  143. the actual C&nbsp;function, add a list of module functions and their
  144. names, add a <tt>luaopen_*</tt> function and register all module
  145. functions, compile and link it into a shared library (DLL), move it to
  146. the proper path, add Lua code that loads the module aaaand ... finally
  147. call the binding function. Phew!
  148. </p>
  149. <h2 id="cdata">Motivating Example: Using C Data Structures</h2>
  150. <p>
  151. The FFI library allows you to create and access C&nbsp;data
  152. structures. Of course, the main use for this is for interfacing with
  153. C&nbsp;functions. But they can be used stand-alone, too.
  154. </p>
  155. <p>
  156. Lua is built upon high-level data types. They are flexible, extensible
  157. and dynamic. That's why we all love Lua so much. Alas, this can be
  158. inefficient for certain tasks, where you'd really want a low-level
  159. data type. E.g. a large array of a fixed structure needs to be
  160. implemented with a big table holding lots of tiny tables. This imposes
  161. both a substantial memory overhead as well as a performance overhead.
  162. </p>
  163. <p>
  164. Here's a sketch of a library that operates on color images, plus a
  165. simple benchmark. First, the plain Lua version:
  166. </p>
  167. <pre class="code">
  168. local floor = math.floor
  169. local function image_ramp_green(n)
  170. local img = {}
  171. local f = 255/(n-1)
  172. for i=1,n do
  173. img[i] = { red = 0, green = floor((i-1)*f), blue = 0, alpha = 255 }
  174. end
  175. return img
  176. end
  177. local function image_to_gray(img, n)
  178. for i=1,n do
  179. local y = floor(0.3*img[i].red + 0.59*img[i].green + 0.11*img[i].blue)
  180. img[i].red = y; img[i].green = y; img[i].blue = y
  181. end
  182. end
  183. local N = 400*400
  184. local img = image_ramp_green(N)
  185. for i=1,1000 do
  186. image_to_gray(img, N)
  187. end
  188. </pre>
  189. <p>
  190. This creates a table with 160.000 pixels, each of which is a table
  191. holding four number values in the range of 0-255. First, an image with
  192. a green ramp is created (1D for simplicity), then the image is
  193. converted to grayscale 1000 times. Yes, that's silly, but I was in
  194. need of a simple example ...
  195. </p>
  196. <p>
  197. And here's the FFI version. The modified parts have been marked in
  198. bold:
  199. </p>
  200. <pre class="code mark">
  201. <span class="codemark">&#9312;
  202. &#9313;
  203. &#9314;
  204. &#9315;
  205. &#9314;
  206. &#9316;</span><b>local ffi = require("ffi")
  207. ffi.cdef[[
  208. </b><span style="color:#00a000;">typedef struct { uint8_t red, green, blue, alpha; } rgba_pixel;</span><b>
  209. ]]</b>
  210. local function image_ramp_green(n)
  211. <b>local img = ffi.new("rgba_pixel[?]", n)</b>
  212. local f = 255/(n-1)
  213. for i=<b>0,n-1</b> do
  214. <b>img[i].green = i*f</b>
  215. <b>img[i].alpha = 255</b>
  216. end
  217. return img
  218. end
  219. local function image_to_grey(img, n)
  220. for i=<b>0,n-1</b> do
  221. local y = <b>0.3*img[i].red + 0.59*img[i].green + 0.11*img[i].blue</b>
  222. img[i].red = y; img[i].green = y; img[i].blue = y
  223. end
  224. end
  225. local N = 400*400
  226. local img = image_ramp_green(N)
  227. for i=1,1000 do
  228. image_to_grey(img, N)
  229. end
  230. </pre>
  231. <p>
  232. Ok, so that wasn't too difficult:
  233. </p>
  234. <p>
  235. <span class="mark">&#9312;</span> First, load the FFI
  236. library and declare the low-level data type. Here we choose a
  237. <tt>struct</tt> which holds four byte fields, one for each component
  238. of a 4x8&nbsp;bit RGBA pixel.
  239. </p>
  240. <p>
  241. <span class="mark">&#9313;</span> Creating the data
  242. structure with <tt>ffi.new()</tt> is straightforward &mdash; the
  243. <tt>'?'</tt> is a placeholder for the number of elements of a
  244. variable-length array.
  245. </p>
  246. <p>
  247. <span class="mark">&#9314;</span> C&nbsp;arrays are
  248. zero-based, so the indexes have to run from <tt>0</tt> to
  249. <tt>n-1</tt>. One might want to allocate one more element instead to
  250. simplify converting legacy code.
  251. </p>
  252. <p>
  253. <span class="mark">&#9315;</span> Since <tt>ffi.new()</tt>
  254. zero-fills the array by default, we only need to set the green and the
  255. alpha fields.
  256. </p>
  257. <p>
  258. <span class="mark">&#9316;</span> The calls to
  259. <tt>math.floor()</tt> can be omitted here, because floating-point
  260. numbers are already truncated towards zero when converting them to an
  261. integer. This happens implicitly when the number is stored in the
  262. fields of each pixel.
  263. </p>
  264. <p>
  265. Now let's have a look at the impact of the changes: first, memory
  266. consumption for the image is down from 22&nbsp;Megabytes to
  267. 640&nbsp;Kilobytes (400*400*4 bytes). That's a factor of 35x less! So,
  268. yes, tables do have a noticeable overhead. BTW: The original program
  269. would consume 40&nbsp;Megabytes in plain Lua (on x64).
  270. </p>
  271. <p>
  272. Next, performance: the pure Lua version runs in 9.57 seconds (52.9
  273. seconds with the Lua interpreter) and the FFI version runs in 0.48
  274. seconds on my machine (YMMV). That's a factor of 20x faster (110x
  275. faster than the Lua interpreter).
  276. </p>
  277. <p style="font-size: 8pt;">
  278. The avid reader may notice that converting the pure Lua version over
  279. to use array indexes for the colors (<tt>[1]</tt> instead of
  280. <tt>.red</tt>, <tt>[2]</tt> instead of <tt>.green</tt> etc.) ought to
  281. be more compact and faster. This is certainly true (by a factor of
  282. ~1.7x). Switching to a struct-of-arrays would help, too.
  283. </p>
  284. <p style="font-size: 8pt;">
  285. However, the resulting code would be less idiomatic and rather
  286. error-prone. And it still doesn't get even close to the performance of
  287. the FFI version of the code. Also, high-level data structures cannot
  288. be easily passed to other C&nbsp;functions, especially I/O functions,
  289. without undue conversion penalties.
  290. </p>
  291. <br class="flush">
  292. </div>
  293. <div id="foot">
  294. <hr class="hide">
  295. Copyright &copy; 2005-2022
  296. <span class="noprint">
  297. &middot;
  298. <a href="contact.html">Contact</a>
  299. </span>
  300. </div>
  301. </body>
  302. </html>