=pod LuaJIT =head1 C API Functions =over =item * LuaJIT =over =item * Download E =item * Installation =item * Running =back =item * Extensions =over =item * FFI Library =over =item * FFI Tutorial =item * ffi.* API =item * FFI Semantics =back =item * jit.* Library =item * Lua/C API =item * Profiler =back =item * Status =over =item * Changes =back =item * FAQ =item * Performance E =item * Wiki E =item * Mailing List E =back This page describes the API functions provided by the FFI library in detail. It's recommended to read through the introduction and the FFI tutorial first. =head2 Glossary =over =item * B E An abstract C type declaration (a Lua string). =item * B E A C type object. This is a special kind of B returned by C. It serves as a B constructor when called. =item * B E A C data object. It holds a value of the corresponding B. =item * B E A C type specification which can be used for most of the API functions. Either a B, a B or a B serving as a template type. =item * B E A callback object. This is a C data object holding a special function pointer. Calling this function from C code runs an associated Lua function. =item * B E A variable-length array is declared with a C instead of the number of elements, e.g. C<"int[?]">. The number of elements (C) must be given when it's created. =item * B E A variable-length struct is a C C type where the last element is a B. The same rules for declaration and creation apply. =back =head2 Declaring and Accessing External Symbols External symbols must be declared first and can then be accessed by indexing a C library namespace, which automatically binds the symbol to a specific library. =head2 C Adds multiple C declarations for types or external symbols (named variables or functions). C must be a Lua string. It's recommended to use the syntactic sugar for string arguments as follows: ffi.cdef[[ typedef struct foo { int a, b; } foo_t; // Declare a struct and typedef. int dofoo(foo_t *f, int n); /* Declare an external C function. */ ]] The contents of the string (the part in green above) must be a sequence of C declarations, separated by semicolons. The trailing semicolon for a single declaration may be omitted. Please note that external symbols are only I, but they are I to any specific address, yet. Binding is achieved with C library namespaces (see below). C declarations are not passed through a C pre-processor, yet. No pre-processor tokens are allowed, except for C<#pragma pack>. Replace C<#define> in existing C header files with C, C or C and/or pass the files through an external C pre-processor (once). Be careful not to include unneeded or redundant declarations from unrelated header files. =head2 C This is the default C library namespace E note the uppercase C<'C'>. It binds to the default set of symbols or libraries on the target system. These are more or less the same as a C compiler would offer by default, without specifying extra link libraries. On POSIX systems, this binds to symbols in the default or global namespace. This includes all exported symbols from the executable and any libraries loaded into the global namespace. This includes at least C, C, C (on Linux), C (if compiled with GCC), as well as any exported symbols from the Lua/C API provided by LuaJIT itself. On Windows systems, this binds to symbols exported from the C<*.exe>, the C (i.e. the Lua/C API provided by LuaJIT itself), the C runtime library LuaJIT was linked with (C), C, C and C. =head2 C This loads the dynamic library given by C and returns a new C library namespace which binds to its symbols. On POSIX systems, if C is C, the library symbols are loaded into the global namespace, too. If C is a path, the library is loaded from this path. Otherwise C is canonicalized in a system-dependent way and searched in the default search path for dynamic libraries: On POSIX systems, if the name contains no dot, the extension C<.so> is appended. Also, the C prefix is prepended if necessary. So C looks for C<"libz.so"> in the default shared library search path. On Windows systems, if the name contains no dot, the extension C<.dll> is appended. So C looks for C<"ws2_32.dll"> in the default DLL search path. =head2 Creating cdata Objects The following API functions create cdata objects (C returns C<"cdata">). All created cdata objects are garbage collected. =head2 cdata = ffi.new(ct [,nelem] [,init...]) cdata = I([nelem,] [init...]) Creates a cdata object for the given C. VLA/VLS types require the C argument. The second syntax uses a ctype as a constructor and is otherwise fully equivalent. The cdata object is initialized according to the rules for initializers, using the optional C arguments. Excess initializers cause an error. Performance notice: if you want to create many objects of one kind, parse the cdecl only once and get its ctype with C. Then use the ctype as a constructor repeatedly. Please note that an anonymous C declaration implicitly creates a new and distinguished ctype every time you use it for C. This is probably B what you want, especially if you create more than one cdata object. Different anonymous C are not considered assignment-compatible by the C standard, even though they may have the same fields! Also, they are considered different types by the JIT-compiler, which may cause an excessive number of traces. It's strongly suggested to either declare a named C or C with C or to create a single ctype object for an anonymous C with C. =head2 C Creates a ctype object for the given C. This function is especially useful to parse a cdecl only once and then use the resulting ctype object as a constructor. =head2 C Creates a scalar cdata object for the given C. The cdata object is initialized with C using the "cast" variant of the C type conversion rules. This functions is mainly useful to override the pointer compatibility checks or to convert pointers to addresses or vice versa. =head2 C Creates a ctype object for the given C and associates it with a metatable. Only C/C types, complex numbers and vectors are allowed. Other types may be wrapped in a C, if needed. The association with a metatable is permanent and cannot be changed afterwards. Neither the contents of the C nor the contents of an C<__index> table (if any) may be modified afterwards. The associated metatable automatically applies to all uses of this type, no matter how the objects are created or where they originate from. Note that pre-defined operations on types have precedence (e.g. declared field names cannot be overridden). All standard Lua metamethods are implemented. These are called directly, without shortcuts and on any mix of types. For binary operations, the left operand is checked first for a valid ctype metamethod. The C<__gc> metamethod only applies to C/C types and performs an implicit C call during creation of an instance. =head2 C Associates a finalizer with a pointer or aggregate cdata object. The cdata object is returned unchanged. This function allows safe integration of unmanaged resources into the automatic memory management of the LuaJIT garbage collector. Typical usage: local p = ffi.gc(ffi.C.malloc(n), ffi.C.free) ... p = nil -- Last reference to p is gone. -- GC will eventually run finalizer: ffi.C.free(p) A cdata finalizer works like the C<__gc> metamethod for userdata objects: when the last reference to a cdata object is gone, the associated finalizer is called with the cdata object as an argument. The finalizer can be a Lua function or a cdata function or cdata function pointer. An existing finalizer can be removed by setting a C finalizer, e.g. right before explicitly deleting a resource: ffi.C.free(ffi.gc(p, nil)) -- Manually free the memory. =head2 C Type Information The following API functions return information about C types. They are most useful for inspecting cdata objects. =head2 C Returns the size of C in bytes. Returns C if the size is not known (e.g. for C<"void"> or function types). Requires C for VLA/VLS types, except for cdata objects. =head2 C Returns the minimum required alignment for C in bytes. =head2 C Returns the offset (in bytes) of C relative to the start of C, which must be a C. Additionally returns the position and the field size (in bits) for bit fields. =head2 C Returns C if C has the C type given by C. Returns C otherwise. C type qualifiers (C etc.) are ignored. Pointers are checked with the standard pointer compatibility rules, but without any special treatment for C. If C specifies a C/C, then a pointer to this type is accepted, too. Otherwise the types must match exactly. Note: this function accepts all kinds of Lua objects for the C argument, but always returns C for non-cdata objects. =head2 Utility Functions =head2 C Returns the error number set by the last C function call which indicated an error condition. If the optional C argument is present, the error number is set to the new value and the previous value is returned. This function offers a portable and OS-independent way to get and set the error number. Note that only I C functions set the error number. And it's only significant if the function actually indicated an error condition (e.g. with a return value of C<-1> or C). Otherwise, it may or may not contain any previously set value. You're advised to call this function only when needed and as close as possible after the return of the related C function. The C value is preserved across hooks, memory allocations, invocations of the JIT compiler and other internal VM activity. The same applies to the value returned by C on Windows, but you need to declare and call it yourself. =head2 C Creates an interned Lua string from the data pointed to by C. If the optional argument C is missing, C is converted to a C<"char *"> and the data is assumed to be zero-terminated. The length of the string is computed with C. Otherwise C is converted to a C<"void *"> and C gives the length of the data. The data may contain embedded zeros and need not be byte-oriented (though this may cause endianess issues). This function is mainly useful to convert (temporary) C<"const char *"> pointers returned by C functions to Lua strings and store them or pass them to other functions expecting a Lua string. The Lua string is an (interned) copy of the data and bears no relation to the original data area anymore. Lua strings are 8 bit clean and may be used to hold arbitrary, non-character data. Performance notice: it's faster to pass the length of the string, if it's known. E.g. when the length is returned by a C call like C. =head2 ffi.copy(dst, src, len) ffi.copy(dst, str) Copies the data pointed to by C to C. C is converted to a C<"void *"> and C is converted to a C<"const void *">. In the first syntax, C gives the number of bytes to copy. Caveat: if C is a Lua string, then C must not exceed C<#src+1>. In the second syntax, the source of the copy must be a Lua string. All bytes of the string I are copied to C (i.e. C<#src+1> bytes). Performance notice: C may be used as a faster (inlinable) replacement for the C library functions C, C and C. =head2 C Fills the data pointed to by C with C constant bytes, given by C. If C is omitted, the data is zero-filled. Performance notice: C may be used as a faster (inlinable) replacement for the C library function C. Please note the different order of arguments! =head2 Target-specific Information =head2 C Returns C if C (a Lua string) applies for the target ABI (Application Binary Interface). Returns C otherwise. The following parameters are currently defined: Parameter Description 32bit 32 bit architecture 64bit 64 bit architecture le Little-endian architecture be Big-endian architecture fpu Target has a hardware FPU softfp softfp calling conventions hardfp hardfp calling conventions eabi EABI variant of the standard ABI win Windows variant of the standard ABI gc64 64 bit GC references =head2 C Contains the target OS name. Same contents as C. =head2 C Contains the target architecture name. Same contents as C. =head2 Methods for Callbacks The C types for callbacks have some extra methods: =head2 C Free the resources associated with a callback. The associated Lua function is unanchored and may be garbage collected. The callback function pointer is no longer valid and must not be called anymore (it may be reused by a subsequently created callback). =head2 C Associate a new Lua function with a callback. The C type of the callback and the callback function pointer are unchanged. This method is useful to dynamically switch the receiver of callbacks without creating a new callback each time and registering it again (e.g. with a GUI library). =head2 Extended Standard Library Functions The following standard library functions have been extended to work with cdata objects: =head2 C Converts a number cdata object to a C and returns it as a Lua number. This is particularly useful for boxed 64 bit integer values. Caveat: this conversion may incur a precision loss. =head2 C Returns a string representation of the value of 64 bit integers (CnnnB> or CnnnB>) or complex numbers (CreEimB>). Otherwise returns a string representation of the C type of a ctype object (C>typeB">>) or a cdata object (C>typeB: >address">), unless you override it with a C<__tostring> metamethod (see C). =head2 iter, obj, start = pairs(cdata) iter, obj, start = ipairs(cdata) Calls the C<__pairs> or C<__ipairs> metamethod of the corresponding ctype. =head2 Extensions to the Lua Parser The parser for Lua source code treats numeric literals with the suffixes C or C as signed or unsigned 64 bit integers. Case doesn't matter, but uppercase is recommended for readability. It handles decimal (C<42LL>), hexadecimal (C<0x2aLL>) and binary (C<0b101010LL>) literals. The imaginary part of complex numbers can be specified by suffixing number literals with C or C, e.g. C<12.5i>. Caveat: you'll need to use C<1i> to get an imaginary part with the value one, since C itself still refers to a variable named C. ---- Copyright E 2005-2017 Mike Pall E Contact =cut #Pod::HTML2Pod conversion notes: #From file ext_ffi_api.html # 21471 bytes of input #Mon May 14 13:19:16 2018 agentzh # No a_name switch not specified, so will not try to render # No a_href switch not specified, so will not try to render # Deleting phrasal "code" element (`tt_157) because it has super-phrasal elements (`br_3, `br_4) as children. # Deleting phrasal "code" element (`tt_113) because it has super-phrasal elements (`br_2) as children. # Deleting phrasal "code" element (`tt_41) because it has super-phrasal elements (`br_1) as children.