Previous: C Type Interoperability, Up: C Interoperability
Go code can call C functions directly using a Go extension implemented
in gccgo: a function declaration may be followed by
__asm__ ("
name")
. For example, here is how the C function
open
can be declared in Go:
func c_open(name *byte, mode int, perm int) int __asm__ ("open");
The C function naturally expects a nul terminated string, which in Go
is equivalent to a pointer to an array (not a slice!) of byte
with a terminating zero byte. So a sample call from Go would look
like (after importing the os
package):
var name = [4]byte{'f', 'o', 'o', 0}; i := c_open(&name[0], os.O_RDONLY, 0);
Note that this serves as an example only. To open a file in Go please
use Go's os.Open
function instead.
The name of Go functions accessed from C is subject to change. At
present the name of a Go function that does not have a receiver is
prefix.package.Functionname
. The prefix is set by the
-fgo-prefix option used when the package is compiled; if the
option is not used, the default is simply go
. To call the
function from C you must set the name using the gcc
extension similar to the gccgo extension.
extern int go_function(int) __asm__ ("myprefix.mypackage.Function");