I have a C++ program that uses some go code compiled to a c library through cgo. I'd like to provide some C delegates / function pointers to the cgo library so that the go code can invoke some code provided by my C++ program. I find many examples how to call go functions from within C++ but nothing vice versa.
My go package looks like this
package main
import (
"fmt"
"unsafe"
)
/*
#include <stdlib.h>
typedef char* (*Callback)(char* args);
*/
import "C"
//export RegisterCallback
func RegisterCallback(funcptr unsafe.Pointer) {
cstr := C.CString("hello from go")
defer C.free(unsafe.Pointer(cstr))
foo := *(*func(*C.char) *C.char)(funcptr)
result := foo(cstr)
fmt.Println(C.GoString((*C.char)(result)))
}
func main() {
}
and I am calling it from C++ like this
char* foo(char* args)
{
std::cout << args;
return "hello from C++";
}
//...
RegisterCallback((void*) &foo);
This, however, crashes badly within go.
extern C) and add any special linkage requirements that your C++ compiler might require for this as well. Then you'll be calling a C function from Go, which is supported. Do not try to call it through a pointer. If you need to do that, export a C function wrapper that calls through a pointer.&foo) and converting it to a data pointer (void *). The only guarantee you get is that you can call a C function (not C++ function) by name, so that's what you have to do:CallC(args). That function, written in plain C (not C++), can take the arguments and use them to pick which C++ function to call in whatever way your C and C++ code are allowed to cooperate by your compilation system.