英文:
How do I pass a **void pointer to C function? I am getting a cgo argument has Go pointer to Go pointer
问题
package main
//
// void test(void** data) {
// // 在这里执行一些操作...
// }
import "C"
import "unsafe"
func main() {
var data *C.void
cData := unsafe.Pointer(&data)
C.test(cData)
}
上面是我尝试做的一个示例,但是我收到一个运行时错误,错误信息是"cgo argument has Go pointer to Go pointer"。我该如何解决这个问题?有什么想法吗?
英文:
package main
//
// void test(data **void) {
// Do something here...
// }
import "C"
import "unsafe"
func main() {
var data *C.void
cData := unsafe.Pointer(&data)
C.test(cData)
}
Above is an example of what I am trying to do but I am receiving a run time error stating cgo argument has Go pointer to Go pointer. How do I resolve this issue? any ideas?
答案1
得分: 0
void*
在 Go 中的等价类型是 unsafe.Pointer
,没有必要声明一个 *C.void
类型的值。你的示例中的错误不是关于一个指向 Go 指针的 Go 指针(这是一个运行时错误),你会得到一个 (variable of type unsafe.Pointer) as *unsafe.Pointer
的错误,这是无法编译的。使用错误中显示的类型:
func main() {
var data unsafe.Pointer
C.test(&data)
}
英文:
The Go equivalent of void*
is an unsafe.Pointer
, there's no reason to declare a value of *C.void
. The error from your example is not about a Go pointer to a Go pointer (which is a runtime error), you will get an error of (variable of type unsafe.Pointer) as *unsafe.Pointer
, which cannot compile. Use the type shown in the error:
func main() {
var data unsafe.Pointer
C.test(&data)
}
答案2
得分: -1
当你声明var data *C.void
时,你是在说data
是Go指针类型。Go中的所有指针都受垃圾回收的管理。
当将&data
传递给unsafe.Pointer
时,会创建另一个Go指针。这就是所谓的“Go指针到Go指针”。它的过程是&data
-> data
-> (void)
。
在这种情况下,垃圾回收器无法确定何时释放data
是合适的,因为&data
指针被传递给了C,C仍然可以通过它访问data
。
请参阅这篇文章了解有关将指针传递给C的更多信息。
除非关闭一些cgo检查(我不建议这样做),否则不可能实现这一点。
英文:
When you declare var data *C.void
, you are saying that data
are Go pointer type. All pointers in Go are subject of garbage collection.
When passing &data
to unsafe.Pointer
another Go pointer is created. Thats what the "Go pointer to Go pointer" means. It goes &data
-> data
-> (void)
.
In this case, garbage collector cannot decide when would be the right time to deallocate data
, because &data
pointer was passed to C, which can still reach data
through it.
See this article about passing pointers to C.
It's not possible, unless you turn-off some of the cgo checks, which I would not recommend.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论