I'm trying to access a DLL on Windows using the following code:

import os

let dll = joinPath(getAppDir(), "DebenuPDFLibrary64DLL1311.dll")

type
  DPL* = object
    id: int32

proc createLibrary(): int32 {.cdecl, dynlib: dll,
  importc: "DPLCreateLibrary".}
proc releaseLibrary(id: int32): void {.cdecl, dynlib: dll,
  importc: "DPLReleaseLibrary".}

proc newDPL*(): DPL =
  result.id = createLibrary()

proc close*(dpl: DPL): void =
  if dpl.id != 0:
    releaseLibrary(dpl.id)

if isMainModule:
  var dpl = newDPL()
  defer: dpl.close()
Here's what happens when I try to compile and run it:
R:\pdfpage>nim c -r debenu.nim
Hint: used config file 'c:\bin\nim\config\nim.cfg' [Conf]
Hint: system [Processing]
Hint: debenu [Processing]
Hint: os [Processing]
Hint: strutils [Processing]
Hint: parseutils [Processing]
Hint: math [Processing]
Hint: algorithm [Processing]
Hint: times [Processing]
Hint: winlean [Processing]
Hint: dynlib [Processing]
CC: debenu
CC: stdlib_system
CC: stdlib_os
CC: stdlib_winlean
Hint:  [Link]
Hint: operation successful (20168 lines compiled; 1.422 sec total; 34.004MiB; Debug Build)
 [SuccessX]
Hint: R:\pdfpage\debenu.exe  [Exec]
No stack traceback available
SIGSEGV: Illegal storage access. (Attempt to read from nil?)
Error: execution of an external program failed: 'R:\pdfpage\debenu.exe '

I'm pretty sure the DLL was compiled using a Microsoft compiler, while Nim, of course, is using gcc.

Can anyone advise?

2017-03-16 10:26:28

If you change your newDPL proc with this?

proc newDPL*(): DPL =
  DPL(id: createLibrary())

Also it's better to use when instead of if for checking whether it's main module or not

when isMainModule:
  mainProc()

2017-03-16 10:43:24

don't use this:

let dll = joinPath(getAppDir(), "DebenuPDFLibrary64DLL1311.dll")

(That's what the OS does for you anyway, it looks up dlls next to your exe.)

Use this:

const dll = "DebenuPDFLibrary64DLL1311.dll"

2017-03-16 11:05:17

Thank you!

I actually used

result = DPL()
because it has several fields to be populated (I cut down the example). I have also switched to not giving the path to the DLL, and now use when instead of if for the isMainModule test.

Incidentally (but related), the WideCString type doesn't seem to be in the docs, or rather it only appears as a function argument. Might be worth adding an index entry for wchar_t* to link to WideCString, and of course, to document it. Anyway, I'll be trying it out later on today...

2017-03-16 11:41:04

@ marksummerfield

Actually there's , check it here

Maybe this is helpful, index and CTRL+F to search what you want

2017-03-16 11:48:11
Yeah, sorry, just found it! 2017-03-16 11:52:18