Conversion C code to GoLang


I want to convert the C code, that reads a DLL generated from Matlab/Simulink:

#include <windows.h>    
void main() {
    // types
    void (*mdl_initialize)(void); // function
    double* mdl_G; // value

    // Dll load
    void* dll = LoadLibrary("./teste_win64.dll");

    // GetProcAddress
  	mdl_initialize = (void(*)(void))GetProcAddress(dll , "initialize");
   	mdl_G = ((double*)GetProcAddress(dll, "G"));
    // Run initialize and capture the G value
    printf("G = %.2f",*mdl_G);

to Golang.

I just tried this tip:

func main() {
    dll, _ := syscall.LoadDLL("./teste_win64.dll")
    mdl_init, _ := syscall.GetProcAddress(dll.Handle, "initialize")
    mdl_G, _ := syscall.GetProcAddress(dll.Handle, "G")
    real_init := (*func())(unsafe.Pointer(&mdl_G))
    real_G := (*float64)(unsafe.Pointer(&mdl_G))

But no success. Any tip?

From WindowsDLLs · golang/go Wiki · GitHub it looks like you need uintptr instead of unsefe.Pointer and syscall instead of trying to convert the pointer to a *func.

I had success using NewLazyDll and NewProc:

dll := syscall.NewLazyDLL("teste_win64.dll")
mdl_G := dll.NewProc("G")
G := (*float64)(unsafe.Pointer(mdl_G.Addr()))

But VSCode report that unsafe.Pointer(mdl_G.Addr()) is misuse. There`s a better form to do this?

1 Like

See cmd/vet: "possible misuse of unsafe.Pointer" check false positive rate may be too high · Issue #41205 · golang/go · GitHub etc

This means you can’t work with the pointers from syscall without go vet falsely complaining about it.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.