GoLang之调用C接口的使用方法

2014-06-10 wcdj


摘要:本文主要介绍在GoLang中如何实现调用C接口。由于Go的官网经常被墙,导致无法浏览官方的详细文档,偶然间在浏览GoLang的源码中找到了一些关于cgo的用法,具体路径在go/misc/cgo目录下。


例如,在go/misc/cgo/gmp/gmp.go文件中可以找到如何在GoLang中引用C Library的方法:

An example of wrapping a C library in Go. This is the GNU multiprecision library gmp's integer type mpz_t wrapped to look like the Go package big's integer type Int.


下面是一个简单的例子:hello.go

完整的代码可以浏览这里:https://github.com/gerryyang/goinaction/blob/master/src/cgo/src/hello.go

package main

/*
#include 
#include 
#include 
#include "../inc/hello.h"

// intentionally write the same LDFLAGS differently
#cgo linux LDFLAGS: -L../lib -lhello
#cgo darwin LDFLAGS: -L../lib -lhello

#if 0
void hello(const char *name)
{
	printf("%s\n", name);
	return;
}
#endif
*/
import "C"

import (
	"fmt"
	"time"
)

func Hello(s string) {
	cs := C.CString(s)
	C.hello(cs)
}

func main() {

	Seed(1000)

	fmt.Println(int(C.random()))
	time.Sleep(time.Duration(1) * time.Second)
	fmt.Println(int(C.random()))

	fmt.Println("getpid:", int(C.getpid()))
	C.puts(C.CString("call C puts"))

	Hello("call C's go wrapper func")
	C.hello(C.CString("call C hello func"))
}

func Seed(i int) {
	C.srandom(C.uint(i))
}

更详细的说明可参考官方的文档:

https://blog.golang.org/c-go-cgo

https://golang.org/cmd/cgo/


例如,字符串在GoLang和C之间的类型转换规则

// Go string to C string
// The C string is allocated in the C heap using malloc.
// It is the caller's responsibility to arrange for it to be
// freed, such as by calling C.free (be sure to include stdlib.h
// if C.free is needed).
func C.CString(string) *C.char

// Go []byte slice to C array
// The C array is allocated in the C heap using malloc.
// It is the caller's responsibility to arrange for it to be
// freed, such as by calling C.free (be sure to include stdlib.h
// if C.free is needed).
func C.CBytes([]byte) unsafe.Pointer

// C string to Go string
func C.GoString(*C.char) string

// C data with explicit length to Go string
func C.GoStringN(*C.char, C.int) string

// C data with explicit length to Go []byte
func C.GoBytes(unsafe.Pointer, C.int) []byte


一个相关的PPT:

Go & cgo: integrating existing C code with Go

http://akrennmair.github.io/golang-cgo-slides/#1


参考

[1] http://www.cnblogs.com/yjf512/archive/2012/07/19/2599304.html

[2] http://tonybai.com/tag/cgo/



你可能感兴趣的:(GoLang,C/C++,Go,in,Action)