从 Go v1.6 开始,cgo 更改了将指针传递给 C 代码golang/go#12416 的规则。从 wiki 的 C 代码调用动态 Go 回调的示例不再有效。
package main
import (
"fmt"
"unsafe"
)
/*
extern void go_callback_int(void* foo, int p1);
// normally you will have to define function or variables
// in another separate C file to avoid the multiple definition
// errors, however, using "static inline" is a nice workaround
// for simple functions like this one.
static inline void CallMyFunction(void* pfoo) {
go_callback_int(pfoo, 5);
}
*/
import "C"
//export go_callback_int
func go_callback_int(pfoo unsafe.Pointer, p1 C.int) {
foo := *(*func(C.int))(pfoo)
foo(p1)
}
func MyCallback(x C.int) {
fmt.Println("callback with", x)
}
// we store it in a global variable so that the garbage collector
// doesn't clean up the memory for any temporary variables created.
var MyCallbackFunc = MyCallback
func Example() {
C.CallMyFunction(unsafe.Pointer(&MyCallbackFunc))
}
func main() {
Example()
}
输出如下所示:
panic: runtime error: cgo argument has Go pointer to Go pointer
今天这样做的正确方法是什么?最好不要像通过将指针转换为 uintptr_t 来隐藏语言中的指针这样的技巧。
当年话下
眼眸繁星
慕容3067478
相关分类