pointers - 将 Go 指针传递给 Cgo
问题描述
我一直在玩 GLFW 绑定,我想通过 glfw.SetUserPointer(...) 将 Queue 结构传递给它,
因此,我这样传递它:
type CircularQueue struct {
Values []interface{}
Front, Rear int32
Capacity int32
}
func newCircularQueue(capacity int32) *CircularQueue {
if capacity < 1 {
log.Fatal("Capacity of Circular Queue Zero or Negative")
}
queue := &CircularQueue{Capacity: capacity}
queue.Values = make([]interface{}, capacity)
return queue
}
...
events := newCircularQueue(16)
window.SetUserPointer(unsafe.Pointer(events))
但我得到一个运行时错误,
panic: runtime error: cgo argument has Go pointer to Go pointer
我做了一些挖掘,看起来……我引用:
Go code may pass a Go pointer to C provided the Go memory to which it
points does not contain any Go pointers. The C code must preserve this
property: it must not store any Go pointers in Go memory, even temporarily.
When passing a pointer to a field in a struct, the Go memory in question is
the memory occupied by the field, not the entire struct. When passing a
pointer to an element in an array or slice, the Go memory in question is the
entire array or the entire backing array of the slice.
但是,我的结构中没有指针,我很困惑:(
解决方案
解决方法很简单。您必须将您提供给 C 代码的内容展平。与其传递循环队列,不如传递数据。
//C
int mysterious_c_func(const char* values, front int32_t, back int32_t, capacity int32_t);
// Go
type CircularQueue struct {
Values []char //this can't possibly work with interface.
Front, Rear int32
Capacity int32
}
...
var q CircularQueue
data := (*C.char)(unsafe.Pointer(q.values))
C.mysterious_c_func(data, C.int(queue.Front), C.int(queue.Rear), C.int(queue.Capacity))
但真正的问题是你试图部分用 C 语言,部分用 Go 语言来实现一个复杂的数据结构。要么实现循环缓冲区
- 在这两种语言中,并允许从数组构造。
- 只有在你真正需要这个概念的地方。
推荐阅读
- reporting-services - 3D 面积图 SSRS 报告第三轴
- powershell - 我们需要每天将“report assinement 09.09.2020.xlsx”(更改日期行 08.09.2020 等不)之类的文件重命名为 myproject.xlsx
- rust - 如何将 dyn FnMut 转换为自定义特征对象?
- java - Akka Streams - 为 mapAsync 定义超时
- list - 如何遍历MyBatis中的动态列表并访问列表的对象
- dataframe - 如何在 Spark 数据框中添加具有当前日期的额外列
- javascript - 试图在我的 React 应用程序中找到给定时间和当前时间的时差(以分钟为单位)
- javascript - 画布闪烁,img.src访问
- c# - 来自外部链接的 PhysicalFileResult 之后的 ASP.NET Core 重定向
- python - 使用 tensorflow 的句子相似度