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))
}
Other workarounds #
Use typedef
and explicitly convert to the type:
package main
/*
#include <stdio.h>
typedef void (*PrintHelloFn)();
static void invoke(void (*f)()) {
f();
}
void printHello() {
printf("Hello, World from C!\n");
}
*/
import "C"
func main() {
C.invoke(C.PrintHelloFn(C.printHello))
}
Useful links #
IBM - CGO callbacks Passing callbacks and pointers to CGO Passing pointers CGO wiki