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.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You want to use cgo. Here's an introduction.
回答2:
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
回答3:
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.