CGO简介
golang与C有着千丝万缕的联系,go代码中可以调用C代码
由于项目需要,新使用的golang语言需要调用C语言写的加解密函数,所以用到了cgo,在此记录一点使用心得
如何调C代码,按C代码的结构分为以下几种
内嵌式
非常简单,只需要两步
- 在golang代码开始部分(
package xxx
之后),添加注释,注释中编写需要使用的C语言代码 - 紧挨着注释结束,另起一行增加
import "C"
,注意跟注释中的C代码紧挨,不要有空行,且不要跟其他golang的import放在一起
这样在golang语言的正文中就可以用C.xxx
的方式调用注释中的C代码了
参考:https://www.jianshu.com/p/45e4aa2e7c2e
本地文件式
这种情况,参考以下的描述,Go编译器也会编译C/C++文件。
When the Go tool sees that one or more Go files use the special import "C", it will look for other non-Go files in the directory and compile them as part of the Go packag