Source Edit

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:

  1. import std/dynlib
  2. type
  3. GreetFunction = proc (): cstring {.gcsafe, stdcall.}
  4. proc loadGreet(lang: string) =
  5. let lib =
  6. case lang
  7. of "french":
  8. loadLib("french.dll")
  9. else:
  10. loadLib("english.dll")
  11. assert lib != nil, "Error loading library"
  12. let greet = cast[GreetFunction](lib.symAddr("greet"))
  13. assert greet != nil, "Error loading 'greet' function from library"
  14. echo greet()
  15. unloadLib(lib)

Imports

strutils

Types

  1. LibHandle = pointer

A handle to a dynamically loaded library. Source Edit

Procs

  1. proc checkedSymAddr(lib: LibHandle; name: cstring): pointer {.
  2. ...raises: [Exception, LibraryError], tags: [RootEffect], forbids: [].}

Retrieves the address of a procedure/variable from lib. Raises LibraryError if the symbol could not be found. Source Edit

  1. proc libCandidates(s: string; dest: var seq[string]) {....raises: [], tags: [],
  2. forbids: [].}

Given a library name pattern s, write possible library names to dest. Source Edit

  1. proc loadLib(): LibHandle {....gcsafe, raises: [], tags: [], forbids: [].}

Gets the handle from the current executable. Returns nil if the library could not be loaded. Source Edit

  1. proc loadLib(path: string; globalSymbols = false): LibHandle {....gcsafe,
  2. raises: [], tags: [], forbids: [].}

Loads a library from path. Returns nil if the library could not be loaded. Source Edit

  1. proc loadLibPattern(pattern: string; globalSymbols = false): LibHandle {.
  2. ...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

  1. proc raiseInvalidLibrary(name: cstring) {.noinline, noreturn,
  2. ...raises: [LibraryError], tags: [], forbids: [].}

Raises a LibraryError exception. Source Edit

  1. proc symAddr(lib: LibHandle; name: cstring): pointer {....gcsafe, raises: [],
  2. tags: [], forbids: [].}

Retrieves the address of a procedure/variable from lib. Returns nil if the symbol could not be found. Source Edit

  1. proc unloadLib(lib: LibHandle) {....gcsafe, raises: [], tags: [], forbids: [].}

Unloads the library lib. Source Edit