使用windows. h将C转换为Golang

xxe27gdn  于 2023-04-18  发布在  Go
关注(0)|答案(1)|浏览(123)

我想把这段代码转换成C语言,这很好用

#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);
}

到GoLang.我刚刚尝试了这个技巧,但不工作:

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)

}

但是不起作用,有什么建议吗?
谢谢

2j4z5cfb

2j4z5cfb1#

错误是不安全指针中的&运算符。方法GetProcAddress已返回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将报告可能的功能误用。但是,根据以下内容,这是正确的:allow conversion of uintptr to unsafe.Pointer when it points to non-Go memory #58625

相关问题