how to import a DLL function written in C using GO?

15,208

Solution 1

You want to use cgo. Here's an introduction.

Solution 2

There are a few ways to do it.

The cgo way allows you to call the function this way:

import ("C")
...
C.SomeDllFunc(...)

It will call libraries basically by "linking" against the library. You can put C code into Go and import the regular C way.

There are more methods such as syscall

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

// ..

kernel32, _        = syscall.LoadLibrary("kernel32.dll")
getModuleHandle, _ = syscall.GetProcAddress(kernel32, "GetModuleHandleW")

...

func GetModuleHandle() (handle uintptr) {
    var nargs uintptr = 0
    if ret, _, callErr := syscall.Syscall(uintptr(getModuleHandle), nargs, 0, 0, 0); callErr != 0 {
    abort("Call GetModuleHandle", callErr)
    } else {
        handle = ret
    }
    return
}

There is this useful github page which describes the process of using a DLL: https://github.com/golang/go/wiki/WindowsDLLs

There are three basic ways to do it.

Solution 3

Use the same method that the Windows port of Go does. See the source code for the Windows implementation of the Go syscall package. Also, take a look at the source code for the experimental Go exp/wingui package

Share:
15,208
The Mask
Author by

The Mask

Updated on October 06, 2022

Comments

  • The Mask
    The Mask about 1 year

    I'm looking for an example code how import a function from a dll written in C. equivalent to DllImport of C#.NET. It's possible? I'm using windows. any help is appreciated. thanks in advance.