2015-10-05 73 views
1

我在C库中有一个结构,里面定义了一些回调。问题去对待这个领域*[0]byte数组类型,我不能将其设置为指针:Cgo:无法在C结构中设置回调

./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二传手,像这样的:

​​

,但它看起来丑陋:我不能通过cb_func作为参数传递给二传手(已经尝试过cb_set(cb_s *s, void(*func)()),但有大约* [0]字节相同的错误)和甲肝e许多类似的回调,因此需要为每对回调函数编写setter。

其他解决方案?

回答

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) 
} 
+0

我已经有差不多有问题注意相同的代码,但在不同的* .c文件代替c包装,以消除双重编译。不管怎么说,还是要谢谢你。 将等待任何其他解决方案,我希望它存在。 – sisoft

+0

是否有其他解决方案? –