This module implements the ability to access symbols from shared libraries. On POSIX this uses the dlsym mechanism, on Windows LoadLibrary.
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.
import dynlib
type
greetFunction = proc(): cstring {.gcsafe, stdcall.}
let lang = stdin.readLine()
let lib = case lang
of "french":
loadLib("french.dll")
else:
loadLib("english.dll")
if lib == nil:
echo "Error loading library"
quit(QuitFailure)
let greet = cast[greetFunction](lib.symAddr("greet"))
if greet == nil:
echo "Error loading 'greet' function from library"
quit(QuitFailure)
let greeting = greet()
echo greeting
unloadLib(lib) LibHandle = pointer
proc raiseInvalidLibrary(name: cstring) {...}{.noinline, noreturn, raises: [LibraryError],
tags: [].}proc checkedSymAddr(lib: LibHandle; name: cstring): pointer {...}{.
raises: [Exception, LibraryError], tags: [RootEffect].}proc libCandidates(s: string; dest: var seq[string]) {...}{.raises: [], tags: [].}proc loadLibPattern(pattern: string; global_symbols = false): LibHandle {...}{.
raises: [Exception], tags: [RootEffect].}proc loadLib(path: string; global_symbols = false): LibHandle {...}{.gcsafe, raises: [],
tags: [].}proc loadLib(): LibHandle {...}{.gcsafe, raises: [], tags: [].}proc unloadLib(lib: LibHandle) {...}{.gcsafe, raises: [], tags: [].}proc symAddr(lib: LibHandle; name: cstring): pointer {...}{.gcsafe, raises: [], tags: [].}
© 2006–2018 Andreas Rumpf
Licensed under the MIT License.
https://nim-lang.org/docs/dynlib.html