doutang6819
2019-08-06 12:56
浏览 243
已采纳

如何将Go函数作为参数传递给C函数?

I'm trying to pass a Go function to a C function.

Something like:

stm := C.struct_tray_menu{
    ....
    fn: // definition of method
    ....
}
C.menu_cb(stm);

and pass that into a C function:

static void menu_cb(struct tray_menu *item) {
  (void)item;
  printf("menu: clicked on %s
", item->text);
}

I'd just like to know how to define something like C.function.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanfu6160 2019-08-07 12:43
    已采纳

    the main problem is misunderstanding of definition of go in c. so final code is look like

    
    //export callOnMeGo
    func callOnMeGo(in int) int {
        fmt.Printf("Go.callOnMeGo(): called with arg = %d
    ", in)
        return  in+ 1
    }
    
    func main() {
    
        C.some_c_func((C.callback_fcn)(unsafe.Pointer(C.callOnMeGo_cgo)))
        //dont forget to use (funcDefinedInGO_cgo) for with postfix _cgo
    
    ...
    
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题