Search⌘ K

Interaction with C and C++

Explore how to interact with C and C++ code in Go using cgo for foreign function interface and SWIG for C++ integration. Learn safe calling conventions, type conversions, memory management, and best practices for combining Go and native code.

We'll cover the following...

Interacting with C

The cgo program provides the mechanism for FFI-support (Foreign Function Interface) to allow safe calling of C libraries from Go code. Here is the link to the primary cgo documentation. The cgo replaces the normal Go-compilers, and it outputs Go and C files that can be combined into a single Go package. It is good practice to combine the calls to C in a separate package. The following import is then necessary in your Go program:

import "C"

and usually also:

import
...