在用go包装某些c库时(如glut),需要将go函数当作回调函数传递给c库(如glutDisplayFunc(&draw)中的draw函数,我想将go写的函数传过去),应该怎么做?我写了一个示例,但一直不成功,不知道为什么?麻烦知道的帮我解答一下。 代码如下:
/ test.h /
extern void SetFunc();
/ test.c /
#include "test.h"
#include "_cgo_export.h"
void SetFunc() { InternalFunc(); }
/ test.go /
package main
// #include "test.h"
import "C"
import "fmt"
var function func()
//export InternalFunc
func InternalFunc() { function() }
func Register(fnct func()) {
function = fnct
C.SetFunc()
}
func test() { fmt.Println("How should I do it") }
func main() { Register(test) }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
go run test.go后出现以下错误:
/tmp/go-build592126733/command-line-arguments/_obj/test.cgo2.o: In function `_cgo_be6c2798e9b7_Cfunc_SetFunc':
/home/shikuijie/桌面/Work/Code/src/test.go:32: undefined reference to `SetFunc' collect2: ld 返回 1
有疑问加站长微信联系(非本文作者)

提示的错误感觉跟回不回调没关系。
你确定普通的cgo跑通了,也就是不回调的这种?
不回调的我用过很多次了,没有问题
要不你给我个方法也行,只要能解决我的问题
编译器找不到SetFunc函数的实现
在 test.h 文件里的声明出错,应该改为这样:
void SetFunc(); extern InternalFunc()
去查下 extern 关键字就知道了。 修改后的代码请见:code
void SetFunc(); extern void InternalFunc();