Dynamic Link instance _lua in Lua

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.