nim 创建 dll(nim学习系列)

发布时间 2023-05-09 22:04:01作者: StudyCat

nim 创建 dll

编译命令

nim c --app:lib --nomain:on test.nim

“--app:lib”表示生成动态链接库(dll)。
“--nomain:on”表示不生成 dllmain 函数。

源代码

test() 是我们自定义的导出函数。

import winim/lean

proc NimMain() {.cdecl, importc.}

proc test(): void {.cdecl, exportc, dynlib.} = 
    MessageBox(0, "test", "Nim is Powerful", 0)

proc DllMain(hinstDLL: HINSTANCE, fdwReason: DWORD, lpvReserved: LPVOID) : BOOL {.stdcall, exportc, dynlib.} =
  NimMain()
  
  case fdwReason:
    of DLL_PROCESS_ATTACH:        
        MessageBox(0, "Hello, world !", "Nim is Powerful", 0)      
    of DLL_PROCESS_DETACH:
      discard
    of DLL_THREAD_ATTACH:
      discard
    of DLL_THREAD_DETACH:
      discard
    else:
      discard      
      
  return true

使用 rundll32 运行,会依次弹出两个窗口。

rundll32 test.dll,test

如下图可以看到有3个导出函数。

自动生成 dllmian

如果不需要自己实现 dllmain 则可以这样写

import winim/lean

proc test(): void {.cdecl, exportc, dynlib.} = 
    MessageBox(0, "test", "Nim is Powerful", 0)

编译命令

nim c --app:lib --nomain:off test.nim

引用

https://nim-lang.org/docs/manual.html#foreign-function-interface-dynlib-pragma-for-export
https://github.com/byt3bl33d3r/OffensiveNim#creating-windows-dlls-with-an-exported-dllmain
https://forum.nim-lang.org/t/1973
https://nim-lang.org/docs/nimc.html
https://peterme.net/dynamic-libraries-in-nim.html
https://learn.microsoft.com/en-us/windows/win32/dlls/dllmain

From: https://www.cnblogs.com/StudyCat/p/17386443.html