Fix doc link.
[luajit-2.0.git] / doc / ext_ffi_api.html
blobe865a5f7a0a75e2b9c49ba1c355f33e4634e8519
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.* API Functions</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 table.abitable { width: 30em; line-height: 1.2; }
13 tr.abihead td { font-weight: bold; }
14 td.abiparam { font-weight: bold; width: 6em; }
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><tt>ffi.*</tt> API Functions</h1>
23 </div>
24 <div id="nav">
25 <ul><li>
26 <a href="luajit.html">LuaJIT</a>
27 <ul><li>
28 <a href="install.html">Installation</a>
29 </li><li>
30 <a href="running.html">Running</a>
31 </li></ul>
32 </li><li>
33 <a href="extensions.html">Extensions</a>
34 <ul><li>
35 <a href="ext_ffi.html">FFI Library</a>
36 <ul><li>
37 <a href="ext_ffi_tutorial.html">FFI Tutorial</a>
38 </li><li>
39 <a class="current" href="ext_ffi_api.html">ffi.* API</a>
40 </li><li>
41 <a href="ext_ffi_semantics.html">FFI Semantics</a>
42 </li></ul>
43 </li><li>
44 <a href="ext_jit.html">jit.* Library</a>
45 </li><li>
46 <a href="ext_c_api.html">Lua/C API</a>
47 </li></ul>
48 </li><li>
49 <a href="status.html">Status</a>
50 <ul><li>
51 <a href="changes.html">Changes</a>
52 </li></ul>
53 </li><li>
54 <a href="faq.html">FAQ</a>
55 </li><li>
56 <a href="http://luajit.org/performance.html">Performance <span class="ext">&raquo;</span></a>
57 </li><li>
58 <a href="http://luajit.org/download.html">Download <span class="ext">&raquo;</span></a>
59 </li></ul>
60 </div>
61 <div id="main">
62 <p>
63 This page describes the API functions provided by the FFI library in
64 detail. It's recommended to read through the
65 <a href="ext_ffi.html">introduction</a> and the
66 <a href="ext_ffi_tutorial.html">FFI tutorial</a> first.
67 </p>
69 <h2 id="glossary">Glossary</h2>
70 <ul>
71 <li><b>cdecl</b> &mdash; An abstract C&nbsp;type declaration (a Lua
72 string).</li>
73 <li><b>ctype</b> &mdash; A C&nbsp;type object. This is a special kind of
74 <b>cdata</b> returned by <tt>ffi.typeof()</tt>. It serves as a
75 <b>cdata</b> <a href="#ffi_new">constructor</a> when called.</li>
76 <li><b>cdata</b> &mdash; A C&nbsp;data object. It holds a value of the
77 corresponding <b>ctype</b>.</li>
78 <li><b>ct</b> &mdash; A C&nbsp;type specification which can be used for
79 most of the API functions. Either a <b>cdecl</b>, a <b>ctype</b> or a
80 <b>cdata</b> serving as a template type.</li>
81 <li><b>VLA</b> &mdash; A variable-length array is declared with a
82 <tt>?</tt> instead of the number of elements, e.g. <tt>"int[?]"</tt>.
83 The number of elements (<tt>nelem</tt>) must be given when it's
84 <a href="#ffi_new">created</a>.</li>
85 <li><b>VLS</b> &mdash; A variable-length struct is a <tt>struct</tt> C
86 type where the last element is a <b>VLA</b>. The same rules for
87 declaration and creation apply.</li>
88 </ul>
90 <h2 id="decl">Declaring and Accessing External Symbols</h2>
91 <p>
92 External symbols must be declared first and can then be accessed by
93 indexing a <a href="ext_ffi_semantics.html#clib">C&nbsp;library
94 namespace</a>, which automatically binds the symbol to a specific
95 library.
96 </p>
98 <h3 id="ffi_cdef"><tt>ffi.cdef(def)</tt></h3>
99 <p>
100 Adds multiple C&nbsp;declarations for types or external symbols (named
101 variables or functions). <tt>def</tt> must be a Lua string. It's
102 recommended to use the syntactic sugar for string arguments as
103 follows:
104 </p>
105 <pre class="code">
106 ffi.cdef[[
107 <span style="color:#00a000;">typedef struct foo { int a, b; } foo_t; // Declare a struct and typedef.
108 int dofoo(foo_t *f, int n); /* Declare an external C function. */</span>
110 </pre>
112 The contents of the string (the part in green above) must be a
113 sequence of
114 <a href="ext_ffi_semantics.html#clang">C&nbsp;declarations</a>,
115 separated by semicolons. The trailing semicolon for a single
116 declaration may be omitted.
117 </p>
119 Please note that external symbols are only <em>declared</em>, but they
120 are <em>not bound</em> to any specific address, yet. Binding is
121 achieved with C&nbsp;library namespaces (see below).
122 </p>
123 <p style="color: #c00000;">
124 C&nbsp;declarations are not passed through a C&nbsp;pre-processor,
125 yet. No pre-processor tokens are allowed, except for
126 <tt>#pragma&nbsp;pack</tt>. Replace <tt>#define</tt> in existing
127 C&nbsp;header files with <tt>enum</tt>, <tt>static&nbsp;const</tt>
128 or <tt>typedef</tt> and/or pass the files through an external
129 C&nbsp;pre-processor (once). Be careful not to include unneeded or
130 redundant declarations from unrelated header files.
131 </p>
133 <h3 id="ffi_C"><tt>ffi.C</tt></h3>
135 This is the default C&nbsp;library namespace &mdash; note the
136 uppercase <tt>'C'</tt>. It binds to the default set of symbols or
137 libraries on the target system. These are more or less the same as a
138 C&nbsp;compiler would offer by default, without specifying extra link
139 libraries.
140 </p>
142 On POSIX systems, this binds to symbols in the default or global
143 namespace. This includes all exported symbols from the executable and
144 any libraries loaded into the global namespace. This includes at least
145 <tt>libc</tt>, <tt>libm</tt>, <tt>libdl</tt> (on Linux),
146 <tt>libgcc</tt> (if compiled with GCC), as well as any exported
147 symbols from the Lua/C&nbsp;API provided by LuaJIT itself.
148 </p>
150 On Windows systems, this binds to symbols exported from the
151 <tt>*.exe</tt>, the <tt>lua51.dll</tt> (i.e. the Lua/C&nbsp;API
152 provided by LuaJIT itself), the C&nbsp;runtime library LuaJIT was linked
153 with (<tt>msvcrt*.dll</tt>), <tt>kernel32.dll</tt>,
154 <tt>user32.dll</tt> and <tt>gdi32.dll</tt>.
155 </p>
157 <h3 id="ffi_load"><tt>clib = ffi.load(name [,global])</tt></h3>
159 This loads the dynamic library given by <tt>name</tt> and returns
160 a new C&nbsp;library namespace which binds to its symbols. On POSIX
161 systems, if <tt>global</tt> is <tt>true</tt>, the library symbols are
162 loaded into the global namespace, too.
163 </p>
165 If <tt>name</tt> is a path, the library is loaded from this path.
166 Otherwise <tt>name</tt> is canonicalized in a system-dependent way and
167 searched in the default search path for dynamic libraries:
168 </p>
170 On POSIX systems, if the name contains no dot, the extension
171 <tt>.so</tt> is appended. Also, the <tt>lib</tt> prefix is prepended
172 if necessary. So <tt>ffi.load("z")</tt> looks for <tt>"libz.so"</tt>
173 in the default shared library search path.
174 </p>
176 On Windows systems, if the name contains no dot, the extension
177 <tt>.dll</tt> is appended. So <tt>ffi.load("ws2_32")</tt> looks for
178 <tt>"ws2_32.dll"</tt> in the default DLL search path.
179 </p>
181 <h2 id="create">Creating cdata Objects</h2>
183 The following API functions create cdata objects (<tt>type()</tt>
184 returns <tt>"cdata"</tt>). All created cdata objects are
185 <a href="ext_ffi_semantics.html#gc">garbage collected</a>.
186 </p>
188 <h3 id="ffi_new"><tt>cdata = ffi.new(ct [,nelem] [,init...])<br>
189 cdata = <em>ctype</em>([nelem,] [init...])</tt></h3>
191 Creates a cdata object for the given <tt>ct</tt>. VLA/VLS types
192 require the <tt>nelem</tt> argument. The second syntax uses a ctype as
193 a constructor and is otherwise fully equivalent.
194 </p>
196 The cdata object is initialized according to the
197 <a href="ext_ffi_semantics.html#init">rules for initializers</a>,
198 using the optional <tt>init</tt> arguments. Excess initializers cause
199 an error.
200 </p>
202 Performance notice: if you want to create many objects of one kind,
203 parse the cdecl only once and get its ctype with
204 <tt>ffi.typeof()</tt>. Then use the ctype as a constructor repeatedly.
205 </p>
206 <p style="font-size: 8pt;">
207 Please note that an anonymous <tt>struct</tt> declaration implicitly
208 creates a new and distinguished ctype every time you use it for
209 <tt>ffi.new()</tt>. This is probably <b>not</b> what you want,
210 especially if you create more than one cdata object. Different anonymous
211 <tt>structs</tt> are not considered assignment-compatible by the
212 C&nbsp;standard, even though they may have the same fields! Also, they
213 are considered different types by the JIT-compiler, which may cause an
214 excessive number of traces. It's strongly suggested to either declare
215 a named <tt>struct</tt> or <tt>typedef</tt> with <tt>ffi.cdef()</tt>
216 or to create a single ctype object for an anonymous <tt>struct</tt>
217 with <tt>ffi.typeof()</tt>.
218 </p>
220 <h3 id="ffi_typeof"><tt>ctype = ffi.typeof(ct)</tt></h3>
222 Creates a ctype object for the given <tt>ct</tt>.
223 </p>
225 This function is especially useful to parse a cdecl only once and then
226 use the resulting ctype object as a <a href="#ffi_new">constructor</a>.
227 </p>
229 <h3 id="ffi_cast"><tt>cdata = ffi.cast(ct, init)</tt></h3>
231 Creates a scalar cdata object for the given <tt>ct</tt>. The cdata
232 object is initialized with <tt>init</tt> using the "cast" variant of
233 the <a href="ext_ffi_semantics.html#convert">C&nbsp;type conversion
234 rules</a>.
235 </p>
237 This functions is mainly useful to override the pointer compatibility
238 checks or to convert pointers to addresses or vice versa.
239 </p>
241 <h3 id="ffi_metatype"><tt>ctype = ffi.metatype(ct, metatable)</tt></h3>
243 Creates a ctype object for the given <tt>ct</tt> and associates it with
244 a metatable. Only <tt>struct</tt>/<tt>union</tt> types, complex numbers
245 and vectors are allowed. Other types may be wrapped in a
246 <tt>struct</tt>, if needed.
247 </p>
249 The association with a metatable is permanent and cannot be changed
250 afterwards. Neither the contents of the <tt>metatable</tt> nor the
251 contents of an <tt>__index</tt> table (if any) may be modified
252 afterwards. The associated metatable automatically applies to all uses
253 of this type, no matter how the objects are created or where they
254 originate from. Note that pre-defined operations on types have
255 precedence (e.g. declared field names cannot be overriden).
256 </p>
258 All standard Lua metamethods are implemented. These are called directly,
259 without shortcuts and on any mix of types. For binary operations, the
260 left operand is checked first for a valid ctype metamethod. The
261 <tt>__gc</tt> metamethod only applies to <tt>struct</tt>/<tt>union</tt>
262 types and performs an implicit <a href="#ffi_gc"><tt>ffi.gc()</tt></a>
263 call during creation of an instance.
264 </p>
266 <h3 id="ffi_gc"><tt>cdata = ffi.gc(cdata, finalizer)</tt></h3>
268 Associates a finalizer with a pointer or aggregate cdata object. The
269 cdata object is returned unchanged.
270 </p>
272 This function allows safe integration of unmanaged resources into the
273 automatic memory management of the LuaJIT garbage collector. Typical
274 usage:
275 </p>
276 <pre class="code">
277 local p = ffi.gc(ffi.C.malloc(n), ffi.C.free)
279 p = nil -- Last reference to p is gone.
280 -- GC will eventually run finalizer: ffi.C.free(p)
281 </pre>
283 A cdata finalizer works like the <tt>__gc</tt> metamethod for userdata
284 objects: when the last reference to a cdata object is gone, the
285 associated finalizer is called with the cdata object as an argument. The
286 finalizer can be a Lua function or a cdata function or cdata function
287 pointer. An existing finalizer can be removed by setting a <tt>nil</tt>
288 finalizer, e.g. right before explicitly deleting a resource:
289 </p>
290 <pre class="code">
291 ffi.C.free(ffi.gc(p, nil)) -- Manually free the memory.
292 </pre>
294 <h2 id="info">C&nbsp;Type Information</h2>
296 The following API functions return information about C&nbsp;types.
297 They are most useful for inspecting cdata objects.
298 </p>
300 <h3 id="ffi_sizeof"><tt>size = ffi.sizeof(ct [,nelem])</tt></h3>
302 Returns the size of <tt>ct</tt> in bytes. Returns <tt>nil</tt> if
303 the size is not known (e.g. for <tt>"void"</tt> or function types).
304 Requires <tt>nelem</tt> for VLA/VLS types, except for cdata objects.
305 </p>
307 <h3 id="ffi_alignof"><tt>align = ffi.alignof(ct)</tt></h3>
309 Returns the minimum required alignment for <tt>ct</tt> in bytes.
310 </p>
312 <h3 id="ffi_offsetof"><tt>ofs [,bpos,bsize] = ffi.offsetof(ct, field)</tt></h3>
314 Returns the offset (in bytes) of <tt>field</tt> relative to the start
315 of <tt>ct</tt>, which must be a <tt>struct</tt>. Additionally returns
316 the position and the field size (in bits) for bit fields.
317 </p>
319 <h3 id="ffi_istype"><tt>status = ffi.istype(ct, obj)</tt></h3>
321 Returns <tt>true</tt> if <tt>obj</tt> has the C&nbsp;type given by
322 <tt>ct</tt>. Returns <tt>false</tt> otherwise.
323 </p>
325 C&nbsp;type qualifiers (<tt>const</tt> etc.) are ignored. Pointers are
326 checked with the standard pointer compatibility rules, but without any
327 special treatment for <tt>void&nbsp;*</tt>. If <tt>ct</tt> specifies a
328 <tt>struct</tt>/<tt>union</tt>, then a pointer to this type is accepted,
329 too. Otherwise the types must match exactly.
330 </p>
332 Note: this function accepts all kinds of Lua objects for the
333 <tt>obj</tt> argument, but always returns <tt>false</tt> for non-cdata
334 objects.
335 </p>
337 <h2 id="util">Utility Functions</h2>
339 <h3 id="ffi_errno"><tt>err = ffi.errno([newerr])</tt></h3>
341 Returns the error number set by the last C&nbsp;function call which
342 indicated an error condition. If the optional <tt>newerr</tt> argument
343 is present, the error number is set to the new value and the previous
344 value is returned.
345 </p>
347 This function offers a portable and OS-independent way to get and set the
348 error number. Note that only <em>some</em> C&nbsp;functions set the error
349 number. And it's only significant if the function actually indicated an
350 error condition (e.g. with a return value of <tt>-1</tt> or
351 <tt>NULL</tt>). Otherwise, it may or may not contain any previously set
352 value.
353 </p>
355 You're advised to call this function only when needed and as close as
356 possible after the return of the related C&nbsp;function. The
357 <tt>errno</tt> value is preserved across hooks, memory allocations,
358 invocations of the JIT compiler and other internal VM activity. The same
359 applies to the value returned by <tt>GetLastError()</tt> on Windows, but
360 you need to declare and call it yourself.
361 </p>
363 <h3 id="ffi_string"><tt>str = ffi.string(ptr [,len])</tt></h3>
365 Creates an interned Lua string from the data pointed to by
366 <tt>ptr</tt>.
367 </p>
369 If the optional argument <tt>len</tt> is missing, <tt>ptr</tt> is
370 converted to a <tt>"char&nbsp;*"</tt> and the data is assumed to be
371 zero-terminated. The length of the string is computed with
372 <tt>strlen()</tt>.
373 </p>
375 Otherwise <tt>ptr</tt> is converted to a <tt>"void&nbsp;*"</tt> and
376 <tt>len</tt> gives the length of the data. The data may contain
377 embedded zeros and need not be byte-oriented (though this may cause
378 endianess issues).
379 </p>
381 This function is mainly useful to convert (temporary)
382 <tt>"const&nbsp;char&nbsp;*"</tt> pointers returned by
383 C&nbsp;functions to Lua strings and store them or pass them to other
384 functions expecting a Lua string. The Lua string is an (interned) copy
385 of the data and bears no relation to the original data area anymore.
386 Lua strings are 8&nbsp;bit clean and may be used to hold arbitrary,
387 non-character data.
388 </p>
390 Performance notice: it's faster to pass the length of the string, if
391 it's known. E.g. when the length is returned by a C&nbsp;call like
392 <tt>sprintf()</tt>.
393 </p>
395 <h3 id="ffi_copy"><tt>ffi.copy(dst, src, len)<br>
396 ffi.copy(dst, str)</tt></h3>
398 Copies the data pointed to by <tt>src</tt> to <tt>dst</tt>.
399 <tt>dst</tt> is converted to a <tt>"void&nbsp;*"</tt> and <tt>src</tt>
400 is converted to a <tt>"const void&nbsp;*"</tt>.
401 </p>
403 In the first syntax, <tt>len</tt> gives the number of bytes to copy.
404 Caveat: if <tt>src</tt> is a Lua string, then <tt>len</tt> must not
405 exceed <tt>#src+1</tt>.
406 </p>
408 In the second syntax, the source of the copy must be a Lua string. All
409 bytes of the string <em>plus a zero-terminator</em> are copied to
410 <tt>dst</tt> (i.e. <tt>#src+1</tt> bytes).
411 </p>
413 Performance notice: <tt>ffi.copy()</tt> may be used as a faster
414 (inlinable) replacement for the C&nbsp;library functions
415 <tt>memcpy()</tt>, <tt>strcpy()</tt> and <tt>strncpy()</tt>.
416 </p>
418 <h3 id="ffi_fill"><tt>ffi.fill(dst, len [,c])</tt></h3>
420 Fills the data pointed to by <tt>dst</tt> with <tt>len</tt> constant
421 bytes, given by <tt>c</tt>. If <tt>c</tt> is omitted, the data is
422 zero-filled.
423 </p>
425 Performance notice: <tt>ffi.fill()</tt> may be used as a faster
426 (inlinable) replacement for the C&nbsp;library function
427 <tt>memset(dst,&nbsp;c,&nbsp;len)</tt>. Please note the different
428 order of arguments!
429 </p>
431 <h2 id="target">Target-specific Information</h2>
433 <h3 id="ffi_abi"><tt>status = ffi.abi(param)</tt></h3>
435 Returns <tt>true</tt> if <tt>param</tt> (a Lua string) applies for the
436 target ABI (Application Binary Interface). Returns <tt>false</tt>
437 otherwise. The following parameters are currently defined:
438 </p>
439 <table class="abitable">
440 <tr class="abihead">
441 <td class="abiparam">Parameter</td>
442 <td class="abidesc">Description</td>
443 </tr>
444 <tr class="odd separate">
445 <td class="abiparam">32bit</td><td class="abidesc">32 bit architecture</td></tr>
446 <tr class="even">
447 <td class="abiparam">64bit</td><td class="abidesc">64 bit architecture</td></tr>
448 <tr class="odd separate">
449 <td class="abiparam">le</td><td class="abidesc">Little-endian architecture</td></tr>
450 <tr class="even">
451 <td class="abiparam">be</td><td class="abidesc">Big-endian architecture</td></tr>
452 <tr class="odd separate">
453 <td class="abiparam">fpu</td><td class="abidesc">Target has a hardware FPU</td></tr>
454 <tr class="even">
455 <td class="abiparam">softfp</td><td class="abidesc">softfp calling conventions</td></tr>
456 <tr class="odd">
457 <td class="abiparam">hardfp</td><td class="abidesc">hardfp calling conventions</td></tr>
458 <tr class="even separate">
459 <td class="abiparam">eabi</td><td class="abidesc">EABI variant of the standard ABI</td></tr>
460 <tr class="odd">
461 <td class="abiparam">win</td><td class="abidesc">Windows variant of the standard ABI</td></tr>
462 </table>
464 <h3 id="ffi_os"><tt>ffi.os</tt></h3>
466 Contains the target OS name. Same contents as
467 <a href="ext_jit.html#jit_os"><tt>jit.os</tt></a>.
468 </p>
470 <h3 id="ffi_arch"><tt>ffi.arch</tt></h3>
472 Contains the target architecture name. Same contents as
473 <a href="ext_jit.html#jit_arch"><tt>jit.arch</tt></a>.
474 </p>
476 <h2 id="extended">Extended Standard Library Functions</h2>
478 The following standard library functions have been extended to work
479 with cdata objects:
480 </p>
482 <h3 id="tonumber"><tt>n = tonumber(cdata)</tt></h3>
484 Converts a number cdata object to a <tt>double</tt> and returns it as
485 a Lua number. This is particularly useful for boxed 64&nbsp;bit
486 integer values. Caveat: this conversion may incur a precision loss.
487 </p>
489 <h3 id="tostring"><tt>s = tostring(cdata)</tt></h3>
491 Returns a string representation of the value of 64&nbsp;bit integers
492 (<tt><b>"</b>nnn<b>LL"</b></tt> or <tt><b>"</b>nnn<b>ULL"</b></tt>) or
493 complex numbers (<tt><b>"</b>re&plusmn;im<b>i"</b></tt>). Otherwise
494 returns a string representation of the C&nbsp;type of a ctype object
495 (<tt><b>"ctype&lt;</b>type<b>&gt;"</b></tt>) or a cdata object
496 (<tt><b>"cdata&lt;</b>type<b>&gt;:&nbsp;</b>address"</tt>).
497 </p>
499 <h2 id="literals">Extensions to the Lua Parser</h2>
501 The parser for Lua source code treats numeric literals with the
502 suffixes <tt>LL</tt> or <tt>ULL</tt> as signed or unsigned 64&nbsp;bit
503 integers. Case doesn't matter, but uppercase is recommended for
504 readability. It handles both decimal (<tt>42LL</tt>) and hexadecimal
505 (<tt>0x2aLL</tt>) literals.
506 </p>
508 The imaginary part of complex numbers can be specified by suffixing
509 number literals with <tt>i</tt> or <tt>I</tt>, e.g. <tt>12.5i</tt>.
510 Caveat: you'll need to use <tt>1i</tt> to get an imaginary part with
511 the value one, since <tt>i</tt> itself still refers to a variable
512 named <tt>i</tt>.
513 </p>
514 <br class="flush">
515 </div>
516 <div id="foot">
517 <hr class="hide">
518 Copyright &copy; 2005-2011 Mike Pall
519 <span class="noprint">
520 &middot;
521 <a href="contact.html">Contact</a>
522 </span>
523 </div>
524 </body>
525 </html>