Search code examples
clua

Lua 5.1 custom loader for a shared object library


How, if at all possible, is it to make a custom function to replace the third searcher in the package.loaders table. From reading the manual require/package.loaders, the manual is unclear how to dynamically link the application with the library.

Once it finds a C library, this searcher first uses a dynamic link facility to link the application with the library...

test
├── example.lua
└── libcexample.so

libcexample.so

require 'libcexample'

What is this dynamic link facility and is it possible to use outside of the normal package loaders?


Solution

  • This is a very OS-specific question, and it is not Lua's place to document how to utilize the APIs provided by your system(s) (or how to implement a dynamic linker entirely).

    5.1/loadlib.c contains the specifics for Lua's implementation(s):

    The default implementation of package.loaders[3] is loader_C, which calls ll_loadfunc, which in turn calls an OS-specific version of ll_load and ll_sym looking for the appropriate entry point (and ll_unloadlib).

    • On Linux/Solaris/BSD/etc., this uses <dlfcn.h>'s dlopen and dlsym (and dlclose).

    • On Darwin (Mac OS X), this uses <dyld.h>'s NSCreateObjectFileImageFromFile and NSLookupSymbolInModule (and NSUnLinkModule).

      • Note that modern Darwin (Mac OS X >= 10.3, macOS) deprecates dyld in favour of dlfcn, so this can be configured to use the latter.
    • On Windows, this uses <windows.h> (<libloaderapi.h>)'s LoadLibraryA and GetProcAddress (and FreeLibrary).

    Note: package.loadlib is ll_loadlib, which also calls ll_loadfunc, but wrapped with different semantics than require / package.loaders[3] per the documentation.

    Of course you can implement all of this yourself, but it requires specific knowledge of your system(s).