项目中项目基本是golang,因为以前的一个库不太好用golang重写,所以只能使用cgo来调用,稍微记录一下
看使用文档
重要的事情说多遍都不为过,一定要仔细看文档:
https://github.com/golang/go/wiki/cgo
注意cgo的注释和 import “C”之间不能有空行!!!
Note that there must be no blank lines in between the cgo comment and the import statement.
package main
/*
#include <stdio.h>
int test() {
return 2016;
}
*/
import "C"
import "fmt"
func main() {
fmt.Println(C.test())
}
编译的时候出错:
could not determine kind of name for C.test
看起来莫名其妙的错误,是这个原因导致的。
Go string 和C string转换
Go string -> C string
func C.CString(goString string) *C.char
转换为C string会分配一个内存,因此需要释放,文档中示例如下
// #include <stdlib.h>
import "C"
import "unsafe"
...
var cmsg *C.char = C.CString("hi")
defer C.free(unsafe.Pointer(cmsg))
// do something with the C string
C string -> Go string
func C.GoString(cString *C.char) string
func C.GoStringN(cString *C.char, length C.int) string
C中的类型使用
C.char
C.schar(signed char)
C.uchar(unsigned char)
C.short
C.ushort(unsigned short)
C.int
C.uint(unsigned int)
C.long
C.ulong(unsigned long)
C.longlong(long long)
C.ulonglong(unsigned long long)
C.float
C.double
其他备注
- 还没来得及深入cgo文档,具体调用机制没看
- cgo性能暂时还没来得及测试