Golang&Python

cgo

2017-10-23  本文已影响79人  风千寻艾

golang与C有着千丝万缕的联系,go代码中可以调用C代码
由于项目需要,新使用的golang语言需要调用C语言写的加解密函数,所以用到了cgo,在此记录一点使用心得

如何调C代码

非常简单,只需要两步

  1. 在golang代码开始部分(package xxx之后),添加注释,注释中编写需要使用的C语言代码
  2. 紧挨着注释结束,另起一行增加import "C",注意跟注释中的C代码紧挨,不要有空行,且不要跟其他golang的import放在一起

这样在golang语言的正文中就可以用C.xxx的方式调用注释中的C代码了

demo
package main

// #include <stdio.h>
// #include <stdlib.h>
/*
void print(char *s) {
    printf("print used by C language:%s\n", s);
}
*/
import "C" //和上一行"*/"直接不能有空行或其他注释

import "unsafe"

func main() {
    s := "hello"
    cs := C.CString(s)
    defer C.free(unsafe.Pointer(cs))
    C.print(cs)
}
原理

其实cgo就是先由编译器识别出import "C"的位置,然后在其上的注释中提取C代码,最后调用C编译器进行分开编译

keypoint

使用cgo要点我觉得有两个

  1. golang和C直接的类型转换
  2. 静态库和动态库的链接
    补充一点当时业务中遇到的问题,要链接的动态库文件,不知道相对路径怎么取,后来找到了解决办法:${SRCDIR}

When the cgo directives are parsed, any occurrence of the string ${SRCDIR} will be replaced by the absolute path to the directory containing the source file.

package aes

/*
#cgo LDFLAGS: -L${SRCDIR} -lyourfile -ldl
#include <stdio.h>
#include <stdlib.h>
#include "yourcode.h"
*/
import "C"

......

掌握了这两点,应该就够用了,具体细节就不在这里写了,请参考官方文档

Reference
http://cholerae.com/2015/05/17/%E4%BD%BF%E7%94%A8Cgo%E7%9A%84%E4%B8%80%E7%82%B9%E6%80%BB%E7%BB%93/

https://golang.org/cmd/cgo/

上一篇下一篇

猜你喜欢

热点阅读