7

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.

The Mask
  • 17,007
  • 37
  • 111
  • 185

3 Answers3

13

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.

Another Prog
  • 841
  • 13
  • 19
6

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

peterSO
  • 158,998
  • 31
  • 281
  • 276
5

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

nmichaels
  • 49,466
  • 12
  • 107
  • 135
  • In advance, thanks for you reply. I getting the following error:`build package main:
 [C:/Go/bin/8g -o teste_go_.8 main.go]
main.go:5: can't find import: C
Error, exit status 1exit status 1` how I fix it? – The Mask Nov 22 '11 at 18:32
  • @TheMask: That may be the subject for a different question. I don't know about using Go on Windows, but my first guess would be to check your environment variables. – nmichaels Nov 22 '11 at 18:41
  • @The Mask: Can you post your error and the way you fixed it as a different question (and answer)? It would probably be helpful to future seekers. – nmichaels Jan 03 '12 at 18:26