今天研究了AllenDang(博客:http://www.cnblogs.com/AllenDang) 写的gform(一个go语言的windows图形库),也顺便学习了如何调用window的dll库。这里用C写了一个简单的功能函数gcd,然后编译打包成dll库。最后,写了一个go的调用例子hello.go。hello.go里面加载dll库,并调用gcd函数获取返回结果。

注意:为了运行例子,需要已经安装好MinGW和go.

 

1、 C写的简单例子。

/* File : example2.c */

 

/* Compute the greatest common divisor of positive integers */

int gcd(int x, int y) {

  int g;

  g = y;

  while (x > 0) {

    g = x;

    x = y % x;

    y = g;

  }

  return g;

}

 

2、 编译dll包。

gcc -c -fpic example2.c

gcc -shared example2.o -o example2.dll

 

3、 Go的访问代码。

// hello.go
package main
import (
    "syscall"
)
func callDll(){
    dll32 := syscall.NewLazyDLL("example2.dll")
    println("call dll:",dll32.Name)
    g:=dll32.NewProc("gcd")
    ret, _, _ :=g.Call(uintptr(4),uintptr(8))
    println()
    println("get the result:",ret)
}
func main() {
    callDll()
}

 

4、 运行例子。

 

go build hello.go

把example2.dll拷贝到hello.go 一样的目录下。然后执行hello.exe.

 

于此类似的,C++代码也可以通过这样的方式被Go所调用。