This module implements the ability to access symbols from shared libraries. On POSIX this uses the dlsym mechanism, on Windows LoadLibrary.
Examples
Loading a simple C function
The following example demonstrates loading a function called greet from a library that is determined at runtime based upon a language choice. If the library fails to load or the function greet is not found, it quits with a failure error code.
Example:
import std/dynlib type GreetFunction = proc (): cstring {.gcsafe, stdcall.} proc loadGreet(lang: string) = let lib = case lang of "french": loadLib("french.dll") else: loadLib("english.dll") assert lib != nil, "Error loading library" let greet = cast[GreetFunction](lib.symAddr("greet")) assert greet != nil, "Error loading 'greet' function from library" echo greet() unloadLib(lib)
Procs
proc loadLibPattern(pattern: string; globalSymbols = false): LibHandle {. ...raises: [Exception], tags: [RootEffect], forbids: [].}
-
Loads a library with name matching pattern, similar to what the dynlib pragma does. Returns nil if the library could not be loaded.Warning: this proc uses the GC and so cannot be used to load the GC.Source Edit
proc raiseInvalidLibrary(name: cstring) {.noinline, noreturn, ...raises: [LibraryError], tags: [], forbids: [].}
- Raises a LibraryError exception. Source Edit