From 5865cd03b7fde1a6922ede584bf4fb6f82db4cd0 Mon Sep 17 00:00:00 2001 From: chai2010 Date: Sun, 18 Feb 2018 03:46:59 +0800 Subject: [PATCH] =?UTF-8?q?ch2-1:=20=E5=A2=9E=E5=8A=A0=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E6=96=B0=E7=9A=84=E4=BE=8B=E5=AD=90,=20=E6=9B=B4=E5=8A=A0Go?= =?UTF-8?q?=E9=A3=8E=E6=A0=BC=E7=9A=84CGO=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ch2-cgo/ch2-01-hello-cgo.md | 26 ++++++++++++++++++++++++++ examples/ch2-01/hello-06/main.go | 23 +++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 examples/ch2-01/hello-06/main.go diff --git a/ch2-cgo/ch2-01-hello-cgo.md b/ch2-cgo/ch2-01-hello-cgo.md index 84b9515..3ec308f 100644 --- a/ch2-cgo/ch2-01-hello-cgo.md +++ b/ch2-cgo/ch2-01-hello-cgo.md @@ -127,6 +127,32 @@ func SayHello(s *C.char) { } ``` + +现在中国版本的CGO代码中C语言代码的比例已经很少了,但是我们依然可以进一步以Go语言的思维来提炼我们的CGO代码。通过分析可以发现`SayHello`函数的参数如果可以直接使用Go字符串是最直接的。在Go1.10中CGO新增加了一个`_GoString_`预定义的C语言类型,用来表示Go语言字符串。下面是改进后的代码: + +```go +// +build go1.10 + +package main + +//void SayHello(_GoString_ s); +import "C" + +import ( + "fmt" +) + +func main() { + C.SayHello("Hello, World\n") +} + +//export SayHello +func SayHello(s string) { + fmt.Print(s) +} +``` + 虽然看起来全部是Go语言代码,但是执行的时候是先从Go语言的`main`函数,到CGO自动生成的C语言版本`SayHello`桥接函数,最后又回到了Go语言环境的`SayHello`函数。虽然看起来有点绕,但CGO确实是这样运行的。 + 需要注意的是,CGO导出Go语言函数时,函数参数中不再支持C语言中`const`修饰符。 diff --git a/examples/ch2-01/hello-06/main.go b/examples/ch2-01/hello-06/main.go new file mode 100644 index 0000000..015d460 --- /dev/null +++ b/examples/ch2-01/hello-06/main.go @@ -0,0 +1,23 @@ +// Copyright © 2017 ChaiShushan . +// License: https://creativecommons.org/licenses/by-nc-sa/4.0/ + +// +build go1.10 + +package main + +//void SayHello(_GoString_ s); +import "C" + +import ( + "fmt" +) + +func main() { + C.SayHello("Hello, World\n") + C.SayHello("") +} + +//export SayHello +func SayHello(s string) { + fmt.Print(s) +}