ch2-cgo/ch2-01-hello-cgo #599
Replies: 5 comments 3 replies
-
给哥哥们避个坑,C的代码一定要和import 在一起贴着,中间不能有空行,如果有空行会找不到C的函数
上面这个例子就是一个错误的例子,会报错 |
Beta Was this translation helpful? Give feedback.
-
Windows系统中, 传中文的情形下, 是乱码的, 能解决么? |
Beta Was this translation helpful? Give feedback.
-
思考题: package main
import (
// _GoString_ 预定义的 C 语言类型
// 注释要和主体部分分开
// void SayHello(_GoString_ s);
"C"
"fmt"
"runtime"
"strconv"
"strings"
)
func GetGoid() int64 {
var (
buf [64]byte
n = runtime.Stack(buf[:], false)
stk = strings.TrimPrefix(string(buf[:n]), "goroutine")
)
idField := strings.Fields(stk)[0]
id, err := strconv.Atoi(idField)
if err != nil {
panic(fmt.Errorf("can not get goroutine id: %v", err))
}
return int64(id)
}
func main() {
fmt.Printf("main %d\n", GetGoid())
C.SayHello("Hello, World\n")
fmt.Printf("main %d\n", GetGoid())
}
// export 紧跟 // 不能有空格
//
//export SayHello
func SayHello(s string) {
fmt.Printf("SayHello %d\n", GetGoid())
fmt.Print(s)
fmt.Printf("SayHello %d\n", GetGoid())
} go run main.go
main 1
SayHello 1
Hello, World
SayHello 1
main 1 |
Beta Was this translation helpful? Give feedback.
-
// +build go1.10 package main //void SayHello(GoString s); import ( func main() { //export SayHello |
Beta Was this translation helpful? Give feedback.
-
// +build go1.10 package main //void SayHello(GoString s); import ( func main() { //export SayHello |
Beta Was this translation helpful? Give feedback.
-
ch2-cgo/ch2-01-hello-cgo
Go语言高级编程
https://chai2010.cn/advanced-go-programming-book/ch2-cgo/ch2-01-hello-cgo.html
Beta Was this translation helpful? Give feedback.
All reactions