Examples of calls between Go and C/C++ (and how to call a Go shared object from Node/Ruby/Python/Java)
Examples of calls between Go and C/C++ and calling Go from dynamic languages.
The examples are designed to work on Mac and Linux. If you're using Windows, feel free to reach out to me to request updates for examples that don't work correctly.
go_to_c
folder)These examples use cgo to enable calls to C.
.a
file): static_c_lib
.so
or .dylib
): dynamic_c_lib
go_to_cxx
folder)C++ has more complex calling conventions (e.g. function overloading, inheritance, templates) and so it uses name mangling which adds a step when calling it from Go. Below are ways to do it.
c_to_go
folder)buildmode=c-archive
from C: static_go_lib
dyn_langs_to_go
folder)Go now allows building a C-compatible dynamically-linked library with buildmode=c-shared
. That allows any language that can call C dynamic libraries to call Go.
There is a cost to calling between languages a Go to C call is about 50x slower than a pure Go call and a Ruby FFI call is about 30x slower than a pure Ruby call. For more details, see the benchmarks section.
Cgo documentation: golang.og/cmd/cgo/
Documentation for go
command (see especially go build
section and "Calling between Go and C"):
golang.org/cmd/go/
SWIG Documentation: swig.org
SWIG Go examples: github.com/swig/swig/tree/master/Examples/go
Gccgo documentation: golang.org/doc/install/gccgo
The code in this repo is MIT Licensed.