Golang与C的关系非常密切,下面主要介绍在Golang中使用C。
##一. Golang中嵌入C代码

  1 package main                                                                                                                    
  2  
  3 //#include <stdio.h>
  4 //#include <stdlib.h>
  5 /*
  6 void Hello(char *str) {
  7     printf("%s\n", str);
  8 }
  9 */
 10 import "C" //假设把C当成包,其实有点类似C++的名字空间
 11 import "unsafe" //C指针的使用,在C代码中申请的空间,GC垃圾回收机制不会管理,所以需要自己手动free申请的空间
 12  
 13 func main() {
 14     s := "Hello Cgo"
 15     cs := C.CString(s)
 16     C.Hello(cs)
 17     C.free(unsafe.Pointer(cs))
 18 }

3,4行的注释也可以写/* */形式
第4行与第5行之间不能有空行,同样第9行与第10行之间也不
能有行,否则编译时cgo会报错:

jack@jack-VirtualBox:~/mygo/src/myC/tmp$ go run goc.go
# command-line-arguments
could not determine kind of name for C.Hello
could not determine kind of name for C.free