Search code examples
cgodlltype-conversion

Convertion C to Golang with windows.h


I want to convert this code in C, that works pretty well

#include <windows.h>

void main() {
    double* mdl_G;
    void* dll = LoadLibrary("./test_win64.dll");
    mdl_G     = ((double*)GetProcAddress(dll, "G"));
    printf("G = %.2f",*mdl_G);
}

to GoLang. I just tried this tip, but doesn`t work:

func main() {

    dll, _ := syscall.LoadDLL("./test_win64.dll")
    mdl_G, _ := syscall.GetProcAddress(dll.Handle, "G")
    real_G := (*float64)(unsafe.Pointer(&mdl_G))
    log.Print(*real_G)

}

But doesnt work. Any suggestions?

Thanks


Solution

  • The error is & operator in unsafe pointer. The method GetProcAddress already return a uintptr.

    func main() {
    
        dll, _ := syscall.LoadDLL("./test_win64.dll")
        mdl_G, _ := syscall.GetProcAddress(dll.Handle, "G")
        real_G := (*float64)(unsafe.Pointer(mdl_G)) // this conversion is safe.
        log.Print(*real_G)
    
    }
    

    Go vet will reports a possible misuse of function. But, that is correct according: allow conversion of uintptr to unsafe.Pointer when it points to non-Go memory #58625