Home  >  Article  >  Backend Development  >  Convert C to Golang using windows.h

Convert C to Golang using windows.h

WBOY
WBOYforward
2024-02-08 23:40:19423browse

使用 windows.h 将 C 转换为 Golang

php editor Zimo will introduce to you how to use windows.h to convert C language code to Golang. Windows.h is the header file of the Windows operating system, which contains many functions and data types used for system programming. By converting C code to Golang, we can use Windows API in the Golang environment to achieve more efficient and flexible program development. This article will introduce you to the conversion steps and precautions in detail to help you successfully complete the conversion from C to Golang and improve development efficiency and code quality.

Question content

I want to convert this code to c language, the effect is very good

#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 go language. I just tried this trick and it 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 it doesn't work. Any suggestions?

Thank you

Solution

The error is the & operator in an unsafe pointer. The getprocaddress method already returns 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 report possible feature abuse. However, this is correct: allow conversion of uintptr to unsafe.pointer when it point to non-go memory#58625

The above is the detailed content of Convert C to Golang using windows.h. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete