Update 03.9.md

This commit is contained in:
无闻
2014-07-28 06:57:28 -04:00
parent 907bdb8976
commit c8dd4416b9

View File

@@ -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 包**