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 d.cc 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(); }

d.cc  extern "C" int C2CppRandom() { return CppRandom(); }

d.cc  int CppRandom() { return random(); }

To make the whole thing work, d.cc 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 https://github.com/wangkuiyi/go-cpp.

About these ads

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

Follow

Get every new post delivered to your Inbox.

Join 31 other followers

%d bloggers like this: