We just saw how to call C code from a Go application using the C package and the import statement. Now, we will see how to call Go code from C, which requires the use of another special statement called export. This is a comment that needs to be placed in the line above the function we want to export, followed by the name of that function:
//export theAnswer
func theAnswer() C.int {
return 42
}
The Go function needs to be declared as external in the C code. This will allow the C code to use it:
extern int theAnswer();
We can test this functionality by creating a Go app that exports a function, which is used by a C function. This gets called inside the Go main function:
package main
// extern int goAdd(int, int);
//
// static int cAdd(int a, int b) {
// return goAdd(a, b);
// }
import "C"
import "fmt"
//export goAdd
func goAdd(a, b C.int) C.int {
return a + b
}
func main() {
fmt.Println(C.cAdd(1, 3))
}
We can see in the preceding example that we have the goAdd function, which is exported to C with the export statement . The export name matches the name of the function, and there are no blank lines between the comment and the function.
We can notice that the types used in the signature of the exported function are not regular Go integers, but C.int variables. We will see how the C and Go systems differ in the next section.