I'm migrating a C # to Go project that requires the use of DLLs, based on this link I started to Working with DLLs in Go, I was able to successfully call several functions but get to a function where I could not move forward.
This is an example of the code in C # that works as expected:
private unsafe delegate int FunctionDelegate(void* handler, ref byte dataType, void* buffer, ref int maxBufferLength, int timeOut);
internal unsafe int ReadData(void* handler, ref byte dataType, void* buffer, ref int maxBufferLength, int timeOut)
{
var funcaddr = GetProcAddress(_dllHandle, "DllFunctionName");
var function = Marshal.GetDelegateForFunctionPointer(funcaddr, typeof(FunctionDelegate)) as FunctionDelegate;
return function.Invoke(handler, ref dataType, buffer,ref maxBufferLength, timeOut);
}
My code in Go:
import (
"fmt"
"syscall"
)
var dll *syscall.DLL
var funcHandlers map[string]*syscall.Proc
func init() {
var err error
funcHandlers = make(map[string]*syscall.Proc)
dll, err = syscall.LoadDLL("DllName.dll")
checkError(err)
}
func loadHandler(hname string) {
//verifica si el handler de la funcion ya se ha cargado
if _, exists := funcHandlers[hname]; exists {
return
}
h, err := dll.FindProc(hname)
checkError(err)
funcHandlers[hname] = h
}
func ReadData(handler uintptr, dataType uintptr, buffer uintptr, maxBufferLength int, timeOut int) (int, error) {
const procName = "DllFunctionName"
//aqui cargo el handler de la funcion en la DLL
loadHandler(procName)
ret, _, err := funcHandlers[procName].Call(handler, dataType, buffer, uintptr(maxBufferLength), uintptr(timeOut))
if fmt.Sprintf("%d", err) != "0" {
return 0, fmt.Errorf("Error al leer los datos. %s", err)
}
return int(ret), nil
}
func checkError(e error) {
if e != nil {
panic(e)
}
}
I call my function in Go as follows:
var dataType byte = 0xFF
var pFrameBuffer = 0x2000
var buffer = make([]byte, 255)
//h corresponde al handler (uintptr) del dispositivo USB, ese me lo retorna una funcion
//de la misma DLL
_, err := RaedData(h, uintptr(dataType), uintptr(unsafe.Pointer(&buffer)), pFrameBuffer, 100)
When executing the function err
it brings the following error:
Error al leer los datos. winapi error #3758161920
I have already searched for the error #3758161920
on the internet and have only found this
that talks about permissions, but does not mention anything about DLLs or Go. I thought at one point that they could be permissions of the folder where the DLL was but it was not, I also thought it was because I was running from VSCode without administrator permissions, but it did not change anything when I gave them those permissions.
With that you give me an idea of where to start, I am well served, thank you in advance.