Thursday, February 26, 2015

Nim and Rusthon


Nim is a new language with some very powerful features. Nim's weakness is interfacing with C++ and external threads, Hankiewicz has a good article on some of these issues here. Nim and Rusthon integration helps solve this problem, allowing you to call Nim functions from C++. This works by including your Nim program in the same markdown file along with a Rusthon program. The embedded Nim program is parsed and wrappers are generated for Nim functions that export to C. During the build Rusthon will use Nim to translate the program to C, and GCC is called to compile a staticlib without a main. The static C library is then linked to the final C++ executeable.


markdown source code

nim

proc my_nim_function(a:cint,b:cint,s:cstring): cint {.cdecl, exportc.} =
 echo("calling my_nim_function")
 echo(s)
 echo("a:", a)
 echo("b:", b)
 result = a+b

rusthon

You need to import nim and in your main function call nim.main() before calling any Nim functions.
#backend:c++
import nim

def main():
 nim.main()
 print 'calling nim function'
 s = 'mymessage to nim'
 msg = my_nim_function( 10, 20, cstr(s) )
 print msg
 print 'ok'

program output

running: /tmp/rusthon-c++-bin
calling nim function
calling my_nim_function
mymessage to nim
a:10
b:20
30
ok

No comments:

Post a Comment