mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-11 23:08:34 +08:00
Update 03.9.md
This commit is contained in:
@@ -10,7 +10,7 @@
|
|||||||
|
|
||||||
// #include <stdio.h>
|
// #include <stdio.h>
|
||||||
// #include <stdlib.h>
|
// #include <stdlib.h>
|
||||||
import “C”
|
import "C"
|
||||||
|
|
||||||
名称 "C" 并不属于标准库的一部分,这只是 cgo 集成的一个特殊名称用于引用 C 的命名空间。在这个命名空间里所包含的 C 类型都可以被使用,例如 C.uint、C.long 等等,还有 libc 中的函数 C.random() 等也可以被调用。
|
名称 "C" 并不属于标准库的一部分,这只是 cgo 集成的一个特殊名称用于引用 C 的命名空间。在这个命名空间里所包含的 C 类型都可以被使用,例如 C.uint、C.long 等等,还有 libc 中的函数 C.random() 等也可以被调用。
|
||||||
|
|
||||||
@@ -26,12 +26,12 @@ Example 3.2 [c1.go](examples/chapter_3/CandGo/c1.go)
|
|||||||
|
|
||||||
package rand
|
package rand
|
||||||
// #include <stdlib.h>
|
// #include <stdlib.h>
|
||||||
import “C”
|
import "C"
|
||||||
func Random() int {
|
func Random() int {
|
||||||
return int(C.random())
|
return int(C.random())
|
||||||
}
|
}
|
||||||
func Seed(i int) {
|
func Seed(i int) {
|
||||||
C.srandom(C.uint(i))
|
C.srandom(C.uint(i))
|
||||||
}
|
}
|
||||||
|
|
||||||
C 当中并没有明确的字符串类型,如果你想要将一个 string 类型的变量从 Go 转换到 C,可以使用 `C.CString(s)`;同样,可以使用 `C.GoString(cs)` 从 C 转换到 Go 中的 string 类型。
|
C 当中并没有明确的字符串类型,如果你想要将一个 string 类型的变量从 Go 转换到 C,可以使用 `C.CString(s)`;同样,可以使用 `C.GoString(cs)` 从 C 转换到 Go 中的 string 类型。
|
||||||
@@ -49,12 +49,12 @@ Example 3.3 [c2.go](examples/chapter_3/CandGo/c2.go)
|
|||||||
package print
|
package print
|
||||||
// #include <stdio.h>
|
// #include <stdio.h>
|
||||||
// #include <stdlib.h>
|
// #include <stdlib.h>
|
||||||
import “C”
|
import "C"
|
||||||
import “unsafe”
|
import "unsafe"
|
||||||
func Print(s string) {
|
func Print(s string) {
|
||||||
cs := C.CString(s)
|
cs := C.CString(s)
|
||||||
defer C.free(unsafe.Pointer(cs))
|
defer C.free(unsafe.Pointer(cs))
|
||||||
C.fputs(cs, (*C.FILE)(C.stdout))
|
C.fputs(cs, (*C.FILE)(C.stdout))
|
||||||
}
|
}
|
||||||
|
|
||||||
**构建 cgo 包**
|
**构建 cgo 包**
|
||||||
@@ -84,4 +84,4 @@ SWIG(简化封装器和接口生成器)支持在 Linux 系统下使用 Go
|
|||||||
|
|
||||||
- [目录](directory.md)
|
- [目录](directory.md)
|
||||||
- 上一节:[Go 性能说明](03.8.md)
|
- 上一节:[Go 性能说明](03.8.md)
|
||||||
- 下一部分:[语言的核心结构与技术](04.1.md)
|
- 下一部分:[语言的核心结构与技术](04.1.md)
|
||||||
|
Reference in New Issue
Block a user