英文:
unexpected type: ... with cgo in Go
问题
我是你的中文翻译助手,以下是你要翻译的内容:
我是Go语言的新手,正在尝试学习如何从Go中调用C语言。我编写了这个程序来打开一个命名信号量,获取其值并将其打印到屏幕上。
当我运行go build semvalue.go
时,我收到以下错误信息:
./semvalue.go:16:14: unexpected type: ...
这是什么意思?我做错了什么?
package main
import "fmt"
// #cgo LDFLAGS: -pthread
// #include <stdlib.h>
// #include <fcntl.h>
// #include <sys/stat.h>
// #include <semaphore.h>
import "C"
func main() {
name := C.CString("/fram")
defer C.free(unsafe.Pointer(name))
fram_sem := C.sem_open(name, C.O_CREAT, C.mode_t(0644), C.uint(1))
var val int
ret := C.sem_getvalue(fram_sem, &val)
fmt.Println(val)
C.sem_close(fram_sem)
}
谢谢。
英文:
I'm new to Go and trying to learn how to call C from Go. I wrote this program to open a named semaphore, get the value and print it to the screen.
When I run it go build semvalue.go
I get the error:
./semvalue.go:16:14: unexpected type: ...
What does this mean? What am I doing wrong?
package main
import "fmt"
// #cgo LDFLAGS: -pthread
// #include <stdlib.h>
// #include <fcntl.h>
// #include <sys/stat.h>
// #include <semaphore.h>
import "C"
func main() {
name := C.CString("/fram")
defer C.free(name)
fram_sem := C.sem_open(name, C.O_CREAT, C.mode_t(0644), C.uint(1))
var val int
ret := C.sem_getvalue(fram_sem, val)
fmt.Println(val)
C.sem_close(fram_sem)
}
Thank you.
答案1
得分: 14
这条消息有些混乱,直到你意识到...
是C函数的可变参数部分。你不能直接从Go中使用C的可变参数函数,所以你需要编写一个小的C包装器来调用sem_open
。
还有几点需要注意:
C.free
应该使用C.free(unsafe.Pointer(name))
进行调用。val
需要是一个*C.int
类型。sem_getvalue
使用了errno
,所以你应该使用ret, err := C.sem_getvalue...
进行调用。
英文:
The message is confusing, until you realize that the ...
is the variadic portion of a C function. You can't use C variadic functions directly from Go, so you'll have to write a small wrapper in C to call sem_open
.
A couple more notes:
C.free
should be called withC.free(unsafe.Pointer(name))
val
needs to be a*C.int
sem_getvalue
useserrno
, so you should call it withret, err := C.sem_getvalue...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论