"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Tips for importing C DLL functions into Go

Tips for importing C DLL functions into Go

Posted on 2025-04-15
Browse:374

How Can I Import C DLL Functions into Go?

Importing a DLL Function into Go using DllImport Equivalent

Problem Statement

In C#, DllImport is used to import functions from a DLL written in C. Is there a similar mechanism available in Go that allows for importing DLL functions created in C?

Solution Using CGO and Syscall

There are multiple approaches to import a DLL function into Go. One method involves using the cgo package, which facilitates the creation of Go bindings for C code. With cgo, you can directly call DLL functions as if they were Go functions.

Another method leverages the syscall package. This allows you to interact with the system's low-level APIs, including DLL loading and function calling. By explicitly managing memory and calling the necessary system functions, you can import DLL functions using syscall.

Example Code for CGO

import "C"

func main() {
    C.SomeDllFunc(...)
}

Example Code for Syscall

import (
    "fmt"
    "syscall"
    "unsafe"
)

func main() {
    kernel32, _ := syscall.LoadLibrary("kernel32.dll")
    getModuleHandle, _ := syscall.GetProcAddress(kernel32, "GetModuleHandleW")

    handle := GetModuleHandle()
    fmt.Println(handle)
}

func GetModuleHandle() uintptr {
    var nargs uintptr = 0
    ret, _, _ := syscall.Syscall(uintptr(getModuleHandle), nargs, 0, 0, 0)
    return ret
}

Additional Resources

For further details, refer to the following resources:

  • [Using DLLs on Windows](https://github.com/golang/go/wiki/WindowsDLLs)
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3