Hello,
I think I am a total n00b since no one seems to talk about this simple idea. But I have been reading the docs and the fora, I still have no clue. I have some C++ files which could be compiled to binaries, but I want to invoke all the functionalities of these C++-files in a nim script. I need to get some user input in nim and then use these C++ functions. So I figured I need to import the functions from the C++ files into my nim project, but.. I don't know how?
I found memlib, where I could get the example to work.
import memlib const dll = staticReadDll("sqlite3_64.dll") proc libversion(): cstring {.cdecl, memlib: dll, importc: "sqlite3_libversion".} echo libversion()
But when I try to do the same with a DLL I compiled my self from
#include <stdio.h>
__declspec(dllexport) void SayHello()
}
and then trying to use
import memlib
const dll = staticReadDll("sample.dll") proc libversion(): cstring {.cdecl, memlib: dll, importc: "SayHello".} echo libversion()
I get the error:
SIGSEGV: Illegal storage access. (Attempt to read from nil?)
I tried many different things. But to no avail.
As you figured, I don't have that much experience with C++. But I don't have the means to rewrite the C++ functions into nim (c2nim didn't work for most of them).
Could someone tell me how to proceed?
Try using dynlib as desrbiced in https://nim-lang.org/docs/manual.html#foreign-function-interface-dynlib-pragma-for-import.
It should look like this :
proc Tcl_Eval(interp: pTcl_Interp, script: cstring): int {.cdecl, importc:"Tcl_Eval",
dynlib:"libtcl(|8.5|8.4|8.3).so.(1|0)".}
The reason you get that SIGSEGV error is because the SayHello function in your C++ code prints "Hello world" but has a void return type, so it doesn't return anything. Then you import that as saying it returns a cstring (which is a pointer to an array of character) and try to print that out. This will obviously not work as the pointer will not point to anything in particular.
That being said what you could do instead (which is the normal thing to do and probably why you haven't found much good data on your approach) is to build the C++ library into your Nim project. So instead of first compiling your C++ code into a DLL, then load that on runtime in Nim from memory you can instead simply build your Nim project together with the C++ project so that it's all one big project. This would likely have caught your bug as well because GCC would complain that the SayHello function didn't return anything. This can be done like this for example: https://github.com/PMunch/badger/blob/master/pgmspace.nim#L3-L10