Go interlanguage call examples
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.
Calls from Go to C (
These examples use cgo to enable calls to C.
- Calling a C snippet in the cgo comment: c_in_comment
- Calling a C statically-linked library (
- Calling a C dynamically-linked library (
Calls from Go to C++ (
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.
- Calling C++ via a C wrapper function: c_wrapper
- Calling C++ via an auto-generated SWIG wrapper: swig
Calls from C/C++ to Go (
- Calling from Go to C and back again: to_c_and_back
- Passing a Go func as function pointer callback to C: callbacks
- Calling a Go static library with
buildmode=c-archivefrom C: static_go_lib
- Calling a Go dynamic lib from C++ cxx_to_go_dyn_lib
- Calling Go from C using gccgo
Calls from Python/Node.js/Ruby/Java to Go (
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.
- Call from Python via ctypes: python_to_go.py
- Call from Node.js via ffi npm module: nodejs_to_go.js
- Call from Ruby via ffi gem: ruby_to_go.rb
- Call from Java via JNA: JavaToGo.java
Cross-language call benchmarks
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/
go command (see especially
go build section and "Calling between Go and C"):
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.