duandanxiu6965
2011-11-22 18:12
浏览 18
已采纳

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

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.

图片转代码服务由CSDN问答提供 功能建议

我正在寻找示例代码,该示例代码如何从用C编写的dll中导入函数,该函数等效于 C#.NET 的DllImport 。 这是可能的? 我正在使用Windows。\感谢您的帮助。 提前致谢。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • drq1257 2011-11-22 18:24
    已采纳

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

    已采纳该答案
    打赏 评论
  • dscs63759 2011-11-22 18:42

    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

    打赏 评论
  • douyi6755 2017-05-14 10:52

    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.

    打赏 评论

相关推荐 更多相似问题