简体   繁体   中英

How to pass a Go function as an argument to a C function?

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\n", item->text);
}

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

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\n", 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

...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM