C functions definition
Before calling C functions inside a Library, they must be defined first.
The function definition permits to understand how to call the C function from Luart and what kind of arguments it takes.
Each function is defined by adding a string
field to the Library instance : it's the C function signature.
Please note that this field must be named as the C function to be called.
C function signature
The function signature is a string
that contains 3 optional fields (only parentheses are required) with the following format :
"[callmethod]
( [arguments]
) [returnvalue]
"
[callmethod]
This field is optional, and is used to define the calling method for the C function, represented by any of the following single character :
character | C calling convention |
---|---|
d |
C default function call |
c |
__cdecl |
s |
stdcall |
f |
fastcall (MSVC) |
F |
fastcall (GNU) |
[arguments]
This field is optional, and is used to define arguments types of the C function, represented by a succession of the following characters :
character | argument type |
---|---|
B |
int (or bool for C++) |
c |
char |
C |
unsigned char |
s |
short / 16bit int / int16_t |
S |
unsigned short / unsigned 16bit int / uint16_t |
i |
32bit int / int32_t |
I |
unsigned 32bit int / uint32_t |
j |
long / 32bit int / int32_t |
J |
unsigned long / unsigned 32bit int / uint32_t |
l |
long long / 64bit int / int64_t |
L |
unsigned long long / 64bit unsigned int / uint64_t |
# |
size_t |
f |
float |
d |
double |
Z |
char* / const char* |
W |
wchar_t* / const wchar_t* |
p |
void* |
u |
union |
. |
struct |
[returnvalue]
This field is optional (if omitted, the C function returns nothing) and is used to define the return type of the C function, represented by a single character, from the same characters list from the [arguments]
field.
C function call
Once the C function have been defined, it can be called as a Lua function by providing Lua arguments (converted to their equivalent in C, see Lua to C conversion rules). You can use any of the following objects as arguments and for return values :
These objects and Lua strings can even be used as pointer argument (this is managed by the C FFI module).Example
local c = require "c"
-- loads the C runtime library
local crt = c.Library()
-- Use the Library instance to define the C function "strstr()"
-- this function takes two arguments of the Z type (const char *)
-- and returns a char * value
-- the convention call is not defined (optional, using default)
crt.strstr = "(ZZ)Z"
-- Calls the defined C function
print(crt.strstr("Hello LuaRT", "RT"))