1. 在Go中引用C代码很简单, 在 import "C"前用注释引入标准的C代码, 然后使用C.xxx的伪包引用C代码空间的标识符即可. 需要注意, import"C"是伪package,不能与其他package一块定义为import (..."C"...)
2. 在Go中引用C代码必须手工释放C代码对象. 释放方法为C.free(unsafe.Pointer(xxx)), 这也要求C代码包含#include <stdlib.h>
3. 必须深入理解下述:
(1) Cgo recognizes this comment above import "C" statement.
(2) Any lines starting with #cgo followed by a space character are removed; these become directives for cgo.
(3) The remaining lines are used as a header when compiling the C parts of the package.
------------------------------------
通俗记忆:
(1)cgo能够识别import "C" 语句的注释.
(2)#cgo行用作cgo指令
(3)其他行用作C头文件
第(2)点很关键! 容易导致重复定义.
实践问题:
代码段1:
-------------------------------
package main
/*
#include <stdlib.h>
#include "prints.h"
*/
import "C"
import (
"fmt"
"unsafe"
)
func main() {
msg := "this is a test for"
cmsg := C.CString(msg)
defer C.free(unsafe.Pointer(cmsg))
C.prints(cmsg)
fmt.Println("done...")
}
//在main包中引入C代码, 使用go run xxx.go会报错. 先go build-->再执行, 无错误.
-------------------------------------
上面解决办法,是定义wrapper把C代码封装起来. 例如:
package myc
/*
#include <stdlib.h>
#include "prints.h"
*/
import "C"
import "unsafe"
func Cprints(msg string) {
cmsg := C.CString(msg)
defer C.free(unsafe.Pointer(cmsg))
C.prints(cmsg)
}
-------------------------------------------------
有疑问加站长微信联系(非本文作者)