英文:
how to import a DLL function written in C using GO?
问题
我正在寻找一个示例代码,用于从用C编写的dll中导入函数。相当于C#.NET的DllImport。这是可能的吗?
我正在使用Windows。
非常感谢您的帮助。提前致谢。
英文:
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
得分: 13
有几种方法可以做到这一点。
cgo的方式允许您以这种方式调用函数:
import "C"
...
C.SomeDllFunc(...)
它将通过“链接”库来调用库。您可以将C代码放入Go中,并以常规的C方式导入。
还有更多的方法,比如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
}
这个有用的GitHub页面描述了使用DLL的过程:
https://github.com/golang/go/wiki/WindowsDLLs
有三种基本的方法可以做到这一点。
英文:
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.
答案2
得分: 6
使用与Go的Windows端口相同的方法。请参考Go syscall包的Windows实现的源代码。此外,还可以查看实验性的Go exp/wingui包的源代码。
英文:
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
得分: 5
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论