Being new to nim, I try to use some external DLL written in C via nim's FFI. 
Several of this DLL API calls look roughly like this: 
    
    
    int do_something(..., char *errMsg);
    

(I replaced all the parameters that are not relevant to my question with `...`)

`do_something()` can succeed returning some non-negative retcode, or it can 
fail and then it returns negative retcode and puts text error message into 
`errMsg` buffer that the caller is supposed to provide. The message is known 
not to exceed 256 chars.

Currently, I call this function like this: 
    
    
    proc do_something(..., errMsg: cstring): cint {.importc, dynlib: 
"doSmth.dll".}
    
    var
      errBuf = newStringOfCap(256).cstring
      retCode = do_something(..., errBuf)
    if retCode < 0:
      echo "ERROR: ", $errBuf
    

This works, but I'm not sure if this a proper way to do it.

I'm not even sure that the anonymous `newStringOfCap(256)` string that backs my 
`errBuf` won't be garbage-collected from under my feet...

Also, `$errBuf` makes string from `errBuf` performing a copy of the `errBuf` 
content. This is not that important in this particular case, but is it possible 
to make it into string without content copying?

Maybe there are some better/more idiomatic alternatives to the above?

Reply via email to