Go语言调用dll动态链接库的简单例子

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

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

 

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所调用。

转载于:https://my.oschina.net/qinhui99/blog/64469

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值