cgo的使用

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

1.快速入手

// 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工具

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.

2.1.操作系统区分

#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语言类型
charC.charbyte
singed charC.scharint8
unsigned charC.ucharuint8
shortC.shortint16
unsigned shortC.ushortuint16
intC.intint32
unsigned intC.uintuint32
longC.longint32
unsigned longC.ulonguint32
long long intC.longlongint64
unsigned long long intC.ulonglonguint64
floatC.floatfloat32
doubleC.doublefloat64
size_tC.size_tuint

4.函数调用

6.实例

10.编译/链接参数

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

参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值