Hello Nim community,
I'm enjoying Nim a great deal, but coming from a scripting language background,
I'm having trouble figuring out some
compiling-and-dynamic-linking-and-memory-related things on my own. Maybe you
can help me?
I have a Linux system, on which I've written a simple library in Nim:
# mylib.nim
func fib*(a: cint): cint {.exportc, cdecl, dynlib.} =
if a <= 0: 0 elif a == 1: 1 else: fib(a - 1) + fib(a - 2)
Run
I compile this library like so:
`nim compile --define:release --app:lib --noMain --out:mylib.so mylib.nim`
Because of reasons, I'd like to call functions in this library from within Perl
5.
Perl lets me use shared libraries via `libffi` (Perl Package
[FFI::Platypus](https://metacpan.org/pod/FFI::Platypus)), and the following
seems to work:
# myprog.pl
use FFI::Platypus;
my $ffi = FFI::Platypus->new(lib=>'./mylib.so');
my $fib = $ffi->function(fib=>['int'] => 'int');
print $fib->call(10); # prints 55
Run
However, based on my understanding of Nim's documentation I highly doubt that
this will work in nontrivial situations, and I lack the skills to debug memory
leaks and segfaults.
I'm wondering:
* Do I have to call `NimMain()` first when interfacing with a shared library
written in Nim?
* If yes, do I have to compile and load `nimrtl` and call `nimrtl.NimMain()`
when interfacing with more than one shared library written in Nim?
* Do I have to protect strings returned by Nim functions from the Garbage
Collector (by copying them before the GC can get them)?
* Are there any other pitfalls I should be aware of?
Kind regards,
Bernhard