Hi all, I am a newbie to Nim and I have tried to write Nim as dynamic library for C, but I got some problems.
person.nim:
import strutils
type
Person = object of RootObj
name*: string
age*: Natural
proc createPerson(n: int):ref Person {.cdecl, exportc: "createPerson", dynlib.} =
var p = new(Person)
p.age = 25
p.name = newString(20)
# p.name = format("jiazequn#$1", n)
return p
proc printPerson(p:ref Person) {.cdecl, exportc: "printPerson", dynlib.} =
echo format("name is $1 and age is $2", p.name, p.age)
proc nim_main() {.cdecl, exportc: "nim_main", dynlib.} =
var num = 0
while true:
num += 1
var p = createPerson(num)
if num mod 10000 == 0:
printPerson(p)
echo num
main.c
#include <stdio.h>
extern void nim_main();
int main()
{
nim_main();
return 0;
}
But I got the following errors when running after a while:
name is and age is 25
2180000
Traceback (most recent call last)
/Users/zachary/Developer/nim-demo/person.nim(24) nim_main
/Users/zachary/Developer/nim-demo/person.nim(16) printPerson
/usr/local/Cellar/nim/1.0.0/nim/lib/pure/strutils.nim(2751) format
/usr/local/Cellar/nim/1.0.0/nim/lib/system/gc.nim(439) newObj
/usr/local/Cellar/nim/1.0.0/nim/lib/system/alloc.nim(777) rawAlloc
SIGSEGV: Illegal storage access. (Attempt to read from nil?)
It seems that it is the GC that cause this problem. If I disable the gc using GC_disable() at the beginning of nim_main(), no error occurred.
Could you please give me some information about how to get it fixed?
Also my final goal is to move nim_main function into main.c, now it have the similar problem.
Thanks!
It works now! Thanks so much, it's of great help.
I also got a question that since I have to call NimMain at startup, is it possible to use multiple nim dynamic libraries in one executable? Do I have to call every NimMain in these dynamic libraries or just one of them?
new*(t: typedesc): auto =