Cgo:无法在Go中设置C-struct中的回调

时间:2015-10-05 11:29:14

标签: go cgo

我在C lib中有一个结构,里面定义了一些回调。问题是将此字段视为*[0]byte数组类型,我无法将其设置为指针:

./test.go:16: cannot use _Cgo_ptr(_Cfpvar_fp_cb_func) (type unsafe.Pointer) as type *[0]byte in assignment

问题代码示例:

package main

/*
void cb_func();
typedef struct cb_s {
    void (*cb_f)();
} cb_s;
*/
import "C"

//export cb_func
func cb_func() {}

func main() {
        var x C.struct_cb_s
        // here I want to set callback cb_f to pointer of cb_func().
        x.cb_f = C.cb_func
}

一种可能的解决方案 - 编写C setter,如下所示:

void cb_set(cb_s *s) {
        s->cb_f = &cb_func;
}

但它看起来很难看:我不能将cb_func作为参数传递给setter(已经尝试cb_set(cb_s *s, void(*func)()),但得到了关于* [0]字节的相同错误)并且有许多类似的回调,所以需要编写setter对于每对回调 - 回调函数。

还有其他解决方案吗?

1 个答案:

答案 0 :(得分:1)

这正是你如何做到的,是的,它是丑陋的。不要忘记将extern void cb_func(void);添加到您的c代码中。

我最终得到了这个:

/*
 typedef struct {
     void (*cb_f)();
 } cb_s;

 extern void cb_func(void);

 static void cb_set(cb_s *s) {
     s->cb_f = &cb_func;
 }
 */
import "C"

//export cb_func
func cb_func() {}

func main() {
    var x C.cb_s
    // here I want to set callback cb_f to pointer of cb_func().
    C.cb_set(&x)
}