如何使用GO导入一个用C编写的DLL函数?

huangapple go评论96阅读模式
英文:

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

你想要使用cgo这里有一个介绍。

英文:

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

huangapple
  • 本文由 发表于 2011年11月23日 02:12:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/8231618.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定