Guest User

proposed hotswap mechanism

a guest
Apr 13th, 2015
294
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Nim 1.23 KB | None | 0 0
  1. import os, dynlib
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8. type
  9.   dlHandle* = ref dlHandleObj
  10.   dlHandleObj = object
  11.     handle*: LibHandle
  12.     path*: string
  13.     loadFuncs: (proc ())
  14.  
  15. proc newDL*(): dlHandle =
  16.   new(result)
  17.  
  18. proc loadDL*(self: dlHandle, path: string, global_symbols: bool = false) =
  19.   self.handle = loadLib(path, global_symbols)
  20.   if self.handle != nil:
  21.     self.path = path
  22.     self.loadFuncs()
  23.   else:
  24.     raise newException(IOError, "dynamic library " & path & " could not be read.")
  25.  
  26. proc unloadDL*(self: dlHandle) =
  27.   unloadLib(self.handle)
  28.   self.handle = nil
  29.   self.path = nil
  30.  
  31.  
  32.  
  33.  
  34.  
  35.  
  36. var foo = newDL()
  37.  
  38. proc something(): string {.importc, dynlib: foo.}
  39.   # when the dynlib pragma is given a dlHandle, it adds the proc to the dlHandle's loadFuncs function.
  40.   # loadFuncs is static at runtime. besides loadFuncs, the compiler is completely unaware of
  41.   # dlHandle's implementation.
  42.  
  43. foo.loadDL(os.getAppDir() / "modules/plugin/libplugin.so")
  44.   # running loadDL makes an attempt to load the library. if it's successful, it runs loadFuncs, giving
  45.   # procs with that dlHandle their symAddrs.
  46.  
  47. proc hello() =
  48.   echo("Hello, ", something(), "!")
  49.     # the dynamic library's procs can now be run without fear of SIGSEGV
  50.  
  51. hello()
Advertisement
Add Comment
Please, Sign In to add comment