CGO passing a function pointer to C
·1 min
By default when passing a function as an argument, Cgo uses unsafe.Pointer. This will result in an IncompatibleAssign error.
In order to pass a function pointer as an argument to a C function, type
conversion must be used. In the example below (*[0]byte)
is used to
convert C.print_hello
to what C.invoke
expects. (*[0]byte)
is
special, it means the same as void *
in C
.
package main
/*
#include <stdio.h>
static void invoke(void (*f)()) {
f();
}
void print_hello() {
printf("Hello, World!\n");
}
*/
import "C"
func main() {
C.invoke((*[0]byte)(C.print_hello))
}