how to import a DLL function written in C using GO

2020-02-09 15:05发布

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.

标签: c dll import go
3条回答
可以哭但决不认输i
2楼-- · 2020-02-09 15:27

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

查看更多
forever°为你锁心
3楼-- · 2020-02-09 15:31

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

查看更多
放荡不羁爱自由
4楼-- · 2020-02-09 15:40

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.

查看更多
登录 后发表回答