Skip to content

Commit

Permalink
Merge pull request #626 from PaiGack/master
Browse files Browse the repository at this point in the history
Update ch2-01-hello-cgo.md
  • Loading branch information
chai2010 committed Apr 23, 2023
2 parents b874ef0 + e0dcbe4 commit 401c701
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 2 deletions.
2 changes: 1 addition & 1 deletion ch2-cgo/ch2-01-hello-cgo.md
Expand Up @@ -174,7 +174,7 @@ func SayHello(s *C.char) {
```go
package main

//#include <hello.h>
//#include "hello.h"
import "C"

func main() {
Expand Down
2 changes: 1 addition & 1 deletion ch2-cgo/ch2-02-basic.md
Expand Up @@ -26,7 +26,7 @@ func main() {
}
```

这个例子展示了 cgo 的基本使用方法。开头的注释中写了要调用的 C 函数和相关的头文件,头文件被 include 之后里面的所有的 C 语言元素都会被加入到”C” 这个虚拟的包中。需要注意的是,import "C" 导入语句需要单独一行,不能与其他包一同 import。向 C 函数传递参数也很简单,就直接转化成对应 C 语言类型传递就可以。如上例中 `C.int(v)` 用于将一个 Go 中的 int 类型值强制类型转换转化为 C 语言中的 int 类型值,然后调用 C 语言定义的 printint 函数进行打印。
这个例子展示了 cgo 的基本使用方法。开头的注释中写了要调用的 C 函数和相关的头文件,头文件被 include 之后里面的所有的 C 语言元素都会被加入到”C” 这个虚拟的包中。import "C" 导入语句推荐单独一行,不与其他包一同 import(在 Go 早期版本中必须单独 import)。向 C 函数传递参数也很简单,就直接转化成对应 C 语言类型传递就可以。如上例中 `C.int(v)` 用于将一个 Go 中的 int 类型值强制类型转换转化为 C 语言中的 int 类型值,然后调用 C 语言定义的 printint 函数进行打印。

需要注意的是,Go 是强类型语言,所以 cgo 中传递的参数类型必须与声明的类型完全一致,而且传递前必须用”C” 中的转化函数转换成对应的 C 类型,不能直接传入 Go 中类型的变量。同时通过虚拟的 C 包导入的 C 语言符号并不需要是大写字母开头,它们不受 Go 语言的导出规则约束。

Expand Down

0 comments on commit 401c701

Please sign in to comment.