Dynamic linkage mechanisms are often used in C language applications to integrate modules; However, the dynamic linkage mechanism is not part of the ANSI C standard, i.e. the implementation method is not portable.
Lua typically does not include any mechanism that cannot be implemented through ANSI C, if dynamic linking is an exception. Lua broke the guidelines for portability and implemented a set of dynamic linkage mechanisms for several platforms.
Package.loadlib is the core function of dynamic link function, receive two parameters: the full path name of dynamic library, function name.
The Loadlib function loads the specified library and links it to Lua, and, as you think, does not call any function in the library, but returns a C function as a LUA function, and returns nil if any errors occur during the load process.
Loadlib is a lower-level function that typically uses require to load the C program library, which searches for the specified library and then calls Loadlib to load the library and returns the initialization function, which registers the functions provided in the library into Lua.
As a simple example:
Copy Code code as follows:
hello.c
#include <stdio.h>
void Hello () {
printf ("hello,world\n");
}
Compiling: Gcc-o libhello.so-fpic-shared hello.c
Copy Code code as follows:
> f = package.loadlib (' ${pathhere}/libhello.so ', ' hello ')
> f ()
Hello,world
The hello () function is simpler, has no parameters, has no return value, and the specific interface specification needs to be studied.