Convertion C to Golang with windows.h

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

Convertion C to Golang with windows.h

问题

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

  1. #include <windows.h>
  2. #include <stdio.h>
  3. int main() {
  4. double* mdl_G;
  5. HMODULE dll = LoadLibrary("./test_win64.dll");
  6. mdl_G = (double*)GetProcAddress(dll, "G");
  7. printf("G = %.2f", *mdl_G);
  8. return 0;
  9. }

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

  1. package main
  2. import (
  3. "log"
  4. "syscall"
  5. "unsafe"
  6. )
  7. func main() {
  8. dll, _ := syscall.LoadDLL("./test_win64.dll")
  9. mdl_G, _ := dll.FindProc("G")
  10. real_G := (*float64)(unsafe.Pointer(&mdl_G))
  11. log.Print(*real_G)
  12. }

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

谢谢。

英文:

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

  1. #include &lt;windows.h&gt;
  2. void main() {
  3. double* mdl_G;
  4. void* dll = LoadLibrary(&quot;./test_win64.dll&quot;);
  5. mdl_G = ((double*)GetProcAddress(dll, &quot;G&quot;));
  6. printf(&quot;G = %.2f&quot;,*mdl_G);
  7. }

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

  1. func main() {
  2. dll, _ := syscall.LoadDLL(&quot;./test_win64.dll&quot;)
  3. mdl_G, _ := syscall.GetProcAddress(dll.Handle, &quot;G&quot;)
  4. real_G := (*float64)(unsafe.Pointer(&amp;mdl_G))
  5. log.Print(*real_G)
  6. }

But doesnt work.
Any suggestions?

Thanks

答案1

得分: 0

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

  1. func main() {
  2. dll, _ := syscall.LoadDLL("./test_win64.dll")
  3. mdl_G, _ := syscall.GetProcAddress(dll.Handle, "G")
  4. real_G := (*float64)(unsafe.Pointer(mdl_G)) // 这个转换是安全的。
  5. log.Print(*real_G)
  6. }

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

英文:

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

  1. func main() {
  2. dll, _ := syscall.LoadDLL(&quot;./test_win64.dll&quot;)
  3. mdl_G, _ := syscall.GetProcAddress(dll.Handle, &quot;G&quot;)
  4. real_G := (*float64)(unsafe.Pointer(mdl_G)) // this conversion is safe.
  5. log.Print(*real_G)
  6. }

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:

确定