ext_ffi.html 9.8 KB

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