Calling C++ from Go without using SWIG

It is known that Go programs can call C routines by using the cgo
command tool. It is also known that SWIG can wrap C++ code into Go
types, which can thus be called by Go programs. By using the trick
explained below, we can make Go programs calling C++ routines without
using SWIG.

Consider that in we defined a C++ routine CppRandom, which
invokes function random declared in stdlib.h, we wrap CppRandom
in multiple levels (as illustrated below) so that the Go program
a.go can call CppRandom.

a.go  func main() { return b.GoRandom() }

b.go  func GoRandom() { return C.CRandom() }

c.c   int CRandom() { return C2CppRandom(); }  extern "C" int C2CppRandom() { return CppRandom(); }  int CppRandom() { return random(); }

To make the whole thing work, should be built into a static
library but with source code files compiled using gcc -fPIC flag;
c.c must be built into a shared library, as required by cgo;
b.go should be built using cgo, and a.go should be built using
go build.

For more details, please refer to the example project at

About these ads

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 36 other followers

%d bloggers like this: