在项目下 创建目录c 与lib目录里面放置c的.c与.h文件
编译生成.so动态链接文件:
gcc -fPIC -shared -o lib/libhi.so c/hi.c
在golang代码里面调用:
import (
"fmt"
"unsafe"
)
/*
#cgo CFLAGS: -I./c //c 代码所在的目录
#cgo LDFLAGS: -L./lib -lhi // .so动态链接文件所在目录 (静态库是一致的)
#include "hi.h"
#include <stdlib.h>
*/
import "C"
func cgoTest() {
d := make([]byte,16)
d = []byte("aabbccdd")
str := C.CString(string(d))
fmt.Println(C.demo(str))
fmt.Println(string(d))
C.free(unsafe.Pointer(str))
}
cgo类型转换表:
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.
unsafe.Pointer (void*)
// Go string to C string
func C.CString(string) *C.char
var val []byte
(*C.char)(unsafe.Pointer(&val[0]))
C.free(unsafe.Pointer(str)) // 释放c的变量