编译Golang包为C语言库文件

Go 1.5发布后,其包含一个特性:可以编译生成C语言动态链接库或静态库。本文给出了示例代码和用法。

go buildgo install命令,可以使用参数 -buildmode 来指定生成哪种类型的二进制目标文件。请见https://golang.org/cmd/go/#Description of build modes 详细说明。

当前我们使用 -buildmode=c-archive 来示例和测试。

Golang源文件:


// file hello.go
package main

  port "C"
import "fmt"

//export SayHello
func SayHello(name string) {
    fmt.Printf("func in Golang SayHello says: Hello, %s!\n", name)
}

//export SayHelloByte
func SayHelloByte(name []byte) {
    fmt.Printf("func in Golang SayHelloByte says: Hello, %s!\n", string(name))
}

//export SayBye
func SayBye() {
    fmt.Println("func in Golang SayBye says: Bye!")
}

func main() {
    // We need the main function to make possible
    // CGO compiler to compile the package as C shared library
}

使用命令go build -buildmode=c-archive -o libhello.a hello.go可以生成一个C语言静态库libhello.a和头文件libhello.h。 然后我们再写个C语言程序来调用这个库,如下:

// file hello.c
#include <stdio.h>
#include "libhello.h"

int main() {
  printf("This is a C Application.\n");
  GoString name = {(char*)"Jane", 4};
  SayHello(name);
  GoSlice buf = {(void*)"Jane", 4, 4};
  SayHelloByte(buf);
  SayBye();
  return 0;
}

使用命令gcc -o hello hello.c libhello.a -pthread来编译生成一个可执行文件hello。执行命令如下:

$ go build -buildmode=c-archive -o libhello.a hello.go
$ gcc -o hello hello.c libhello.a -pthread
$ ./hello 
This is a C Application.
func in Golang SayHello says: Hello, Jane!
func in Golang SayHelloByte says: Hello, Jane!
func in Golang SayBye says: Bye!

备注:目前Golang还不支持将一个struct结构导出到C库中。

参考

  1. Sharing Golang packages to C and Go

转载于:https://my.oschina.net/mickelfeng/blog/2252565

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值