英文:
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 <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
答案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("./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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论