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.