@mantielero Nim does not support creating functions at runtime. Generally, 
compiled languages such as Nim get around this by compiling a source file into 
a DLL and then loading that. It's unfortunately not as simple as you want it to 
be.

The library @Hlaaftana linked to is being created by @shashlick (which is 
probably not ready yet) and it will likely allow an easy interface for creating 
plugins in Nim.

In the meantime, this is how you would do it. Put the following 3 files in the 
same directory.
    
    
    # english.nim
    proc greet*(): string {.exportc, dynlib, cdecl.} =
      result = "Hello!"
    
    
    Run

Compile the above with `nim c --app:lib english.nim`. This will result in 
`libenglish.dylib` on Mac, `libenglish.so` on other Unix, and `english.dll` on 
Windows.
    
    
    # french.nim
    proc greet*(): string {.exportc, dynlib, cdecl.} =
      result = "Hello!"
    
    
    Run

Compile the above with `nim c --app:lib french.nim`. This will result in 
`libfrench.dylib` on Mac, `libfrench.so` on other Unix, and `french.dll` on 
Windows.
    
    
    # testplugin.nim
    import dynlib
    
    type
      greetFunction = proc(): string {.nimcall.}
    
    proc main() =
      echo "Enter a language: "
      let lang = stdin.readLine()
      
      let lib = case lang
      of "french":
        loadLib("./libfrench.dylib") # Rename for your OS
      else:
        loadLib("./libenglish.dylib") # Rename for your OS
      
      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)
    
    main()
    
    
    Run

Then compile and run the above with `nim c -r testplugin.nim`. You should get a 
prompt to enter your language. Enter "french" for "Bonjour!" or anything else 
for "Hello!".

You could easily extend the above to get a function name from a list of plugin 
paths. Hope this is helpful to you.

Reply via email to