Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a nim dll and call it from c#

I have read almost every example I could find via google, and couldn't accomplish the simplest task creating a dll (windows)from nim

Could anyone explain it step by step?

I am using the nim IDE - aporia to produce the code.

Does building a dll require the use of the command line? I guess there's a workaround.

using aporia IDE \ command line, how can one achive the same result as done by compiling code below to a dll:

extern "C" __declspec(dllexport) int __stdcall return_multiply(int num1, int num2)
{
    return num1 * num2;
}

that code as you probably know could be called from c#

like image 433
Avia Afer Avatar asked Oct 26 '15 14:10

Avia Afer


1 Answers

Steps in a nutshell:

  1. Define your proc using the pragmas {.stdcall,exportc,dynlib.}
  2. Compile with --app:lib

Remember that you can always inspect the generated C code to see what is going on. So, let's start with a file test.nim containing:

proc return_multiply(num1, num2: int): int {.stdcall,exportc,dynlib.} =
  num1 * num2

Compiling this with nim c --app:lib -d:release test.nim produces the DLL along with this code (in the nimcache folder):

N_LIB_EXPORT N_STDCALL(NI, return_multiply)(NI num1, NI num2) {
        NI result;
        result = 0;
        result = (NI)(num1 * num2);
        return result;
}

You can lookup these macros in nimbase.h. For instance N_LIB_EXPORT is defined as follows for Windows:

#  ifdef __cplusplus
#    define N_LIB_EXPORT  extern "C" __declspec(dllexport)
#  else
#    define N_LIB_EXPORT  extern __declspec(dllexport)
#  endif
#  define N_LIB_IMPORT  extern __declspec(dllimport)

Overall, you will end up with exactly the function signature you have given.

If you do not want to compile by using the command line, you have to figure out which Aporia settings enables --app:lib.

like image 142
bluenote10 Avatar answered Sep 22 '22 19:09

bluenote10