C++ bindings in Go and Swig

- go c++ swig

Swig is a tool to generate bindings for c/c++, it can produce bindings for Python, Java, Go and more.

Unfortunately Swig for Go is very limited, so as the Swig & Go documentation.
Here are some notes taken while writing a binding from c++ to Go:

To bind standard types into Golang

Let’s look at this c++ function:

int64_t Ticks() const;

Simply include sdtint into Swig

%include "stdint.i"

It will translate into Go

func Ticks() int64

To bind std::string as Go string

Includes std_string.i to transform them into string

%include "std_string.i"

Using std::list & std::vector

This example function returns a vector of structs.

std::vector<struct PassDetails> GeneratePassList(
                                               const double lat,
                                               const double lng);

Help Swig with these imports

%include <typemaps.i>
%include "std_vector.i"

namespace std {
   %template(PassDetailsVector) vector<PassDetails>;
}

Translates into Go

func GeneratePassList(arg1 float64, arg2 float64) (_swig_ret PassDetailsVector) 

Then use the generated helpers to access the elements

cdetails := cppsgp4.GeneratePassList(lat, lng)
for i := 0; i < int(cdetails.Capacity()); i++ {
  cpd := cdetails.Get(i)
  ...
}

Transforming c++ exceptions into Go errors

Tell swig about it:

%include "exception.i"
%exception {
    try {
        $action;
    } catch (std::runtime_error &e) {
        _swig_gopanic(e.what());
    }
}

Here is a c++ class which can raise exceptions

class Tle {
public:
    Tle(const std::string& line_one, const std::string& line_two);

Wrap the real function into yours, catch the panic and transform into error

type TLE struct {
    ctle cppsgp4.Tle
}

func NewTLE(tle1, tle2 string) (tle *TLE, err error) {
    defer catch(&err)
    ctle := cppsgp4.NewTle(tle1, tle2)

    tle = &TLE{ctle: ctle}
    return tle, nil
}

Invocation

swig -c++ -intgosize 64 -go myfile.i

Go can find your swig file if they end with the.swigextension.

Example

I’m writing a binding for a satellites pass prediction, you may find some codes useful.