Convertion C to Golang with windows.h

huangapple go评论86阅读模式
英文:

Convertion C to Golang with windows.h

问题

我想将这段代码转换成C语言,它运行得很好。

#include <windows.h>
#include <stdio.h>

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

转换成Go语言后,我尝试了以下代码,但是不起作用:

package main

import (
	"log"
	"syscall"
	"unsafe"
)

func main() {
	dll, _ := syscall.LoadDLL("./test_win64.dll")
	mdl_G, _ := dll.FindProc("G")
	real_G := (*float64)(unsafe.Pointer(&mdl_G))
	log.Print(*real_G)
}

但是它不起作用。有什么建议吗?

谢谢。

英文:

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

#include &lt;windows.h&gt;

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

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

func main() {

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

}

But doesnt work.
Any suggestions?

Thanks

答案1

得分: 0

错误是在不安全指针中的&运算符。
方法GetProcAddress已经返回一个uintptr。

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)

}

Go vet将报告可能的函数误用。但是,根据允许将uintptr转换为指向非Go内存的unsafe.Pointer #58625,这是正确的。

英文:

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

func main() {

    dll, _ := syscall.LoadDLL(&quot;./test_win64.dll&quot;)
    mdl_G, _ := syscall.GetProcAddress(dll.Handle, &quot;G&quot;)
    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

huangapple
  • 本文由 发表于 2023年3月8日 03:48:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75666562.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定