意外类型:在Go中使用cgo时…

huangapple go评论77阅读模式
英文:

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 &quot;fmt&quot;

// #cgo LDFLAGS: -pthread
// #include &lt;stdlib.h&gt;
// #include &lt;fcntl.h&gt;
// #include &lt;sys/stat.h&gt;
// #include &lt;semaphore.h&gt;
import &quot;C&quot;

func main() {
	name := C.CString(&quot;/fram&quot;)
	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 with C.free(unsafe.Pointer(name))
  • val needs to be a *C.int
  • sem_getvalue uses errno, so you should call it with ret, err := C.sem_getvalue...

huangapple
  • 本文由 发表于 2014年11月11日 04:28:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/26852407.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定