Abel'Blog

我干了什么?究竟拿了时间换了什么?

0%

go-cgo的使用

前言

golang可以通过cgo直接来调用c/c++的函数代码。这里是参考《Go语言高级编程》书,做一些笔记。结构按照书的章节来。

1.快速入手

1
2
3
4
5
6
7
8
// hello.go
package main

import "C"

func main() {
println("hello cgo")
}

2.CGO基础

需要安装C/C++构建工具链,在macOS和Linux下是要安装GCC,在windows下是需要安装MinGW工具。同时需要保证环境变量CGO_ENABLED被设置为1,这表示CGO是被启用的状态。

Windows里面使用的MinGW工具

1
2
3
4
5
6
7
8
9
10
11
12
13
14
mingw64\mingw64\bin>.\g++.exe --version
g++.exe (x86_64-win32-seh-rev0, Built by MinGW-W64 project) 8.1.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

// 在 strawberryperl 也有一个版本。
PS D:\work\trunk\doc> gcc --version
gcc.exe (x86_64-posix-seh, Built by strawberryperl.com project) 8.3.0
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

It includes perl binaries, compiler (gcc) + related tools, all the external libraries (crypto, math, graphics, xml…), all the bundled database clients and all you expect from Strawberry Perl.

gcc编译器对标准支持情况 gcc 8.x 版本的编译器已经能编译大部分c++17标准的东西了。

2.1.操作系统区分

1
2
3
##cgo windows CFLAGS: -DCGO_OS_WINDOWS=1
##cgo darwin CFLAGS: -DCGO_OS_DARWIN=1
##cgo linux CFLAGS: -DCGO_OS_LINUX=1

3.类型转换

C语言类型 CGO类型 Go语言类型
char C.char byte
singed char C.schar int8
unsigned char C.uchar uint8
short C.short int16
unsigned short C.ushort uint16
int C.int int32
unsigned int C.uint uint32
long C.long int32
unsigned long C.ulong uint32
long long int C.longlong int64
unsigned long long int C.ulonglong uint64
float C.float float32
double C.double float64
size_t C.size_t uint

4.函数调用

6.实例

10.编译/链接参数

1
2
3
4
因此CGO提供了CFLAGS/CPPFLAGS/CXXFLAGS三种参数,
其中CFLAGS对应C语言编译参数(以.c后缀名)、
CPPFLAGS对应C/C++ 代码编译参数(.c,.cc,.cpp,.cxx)、
CXXFLAGS对应纯C++编译参数(.cc,.cpp,*.cxx)。

参考