# 22 SWIG and Go

- Overview
- Running SWIG with Go
  - Additional Commandline Options
  - Go Output Files
- A tour of basic C/C++ wrapping
  - Go Package Name
  - Go Names
  - Go Constants
  - Go Enumerations
  - Go Classes
    - Go Class Inheritance
  - Go Templates
  - Go Director Classes
  - Default Go primitive type mappings
  - Output arguments
  - Adding additional go code

This chapter describes SWIG's support of Go. For more information on the Go programming language see golang.org.

## 22.1 Overview

Go is a compiled language, not a scripting language. However, it does not support direct calling of functions written in C/C++. The cgo program may be used to generate wrappers to call C code from Go, but there is no convenient way to call C++ code. SWIG fills this gap.

There are (at least) two different Go compilers. One is the gc compiler, normally invoked under the names 6g, 8g, or 5g. The other is the gccgo compiler, which is a frontend to the gcc compiler suite. The interface to C/C++ code is completely different for the two Go compilers. SWIG supports both, selected by a command line option.

Because Go is a type-safe compiled language, SWIG's runtime type checking and runtime library are not used with Go. This should be borne in mind when reading the rest of the SWIG documentation.

## 22.2 Running SWIG with Go

To generate Go code, use the `-go` option with SWIG. By default SWIG will generate code for the gc compilers. To generate code for gccgo, you should also use the `-gccgo` option.

### 22.2.1 Additional Commandline Options

These are the command line options for SWIG's GO module. They can also be seen by using:

    swig -go -help

Go specific options
-gccgo | Generate code for gccgo. The default is to generate code for 6g/8g/5g.
-package <name> | Set the name of the Go package to <name>. The default package name is the SWIG module name.
-soname %lt;name%gt; | Set the runtime name of the shared library that the dynamic linker should include at runtime. The default is the package name with ".so" appended. This is only used when generating code for 6g/8g/5g; when using gccgo, the equivalent name will be taken from the `-soname` option passed to the linker.
-go-prefix <prefix> | When generating code for gccgo, set the prefix to use. This corresponds to the `-fgo-prefix` option to gccgo.
-long-type-size <s> | Set the size for the C/C++ type `long`. This controls whether `long` is converted to the Go type `int32` or `int64`. The <s> argument should be 32 or 64.

### 22.2.2 Go Output Files

When generating Go code, SWIG will generate the following files:

- MODULE.go will contain the Go functions that your Go code will call. These functions will be wrappers for the C++ functions defined by your module. This file should, of course, be compiled with the Go compiler.
- MODULE_wrap.c or MODULE_wrap.cxx will contain C/C++ functions will be invoked by the Go wrapper code. This file should be compiled with the usual C or C++ compiler and linked into a shared library.
- MODULE_wrap.h will be generated if you use the directors feature. It provides a definition of the generated C++ director classes. It is generally not necessary to use this file, but in some special cases it may be helpful to include it in your code, compiled with the usual C or C++ compiler.
- If using the gc compiler, MODULE_gc.c will contain C code which should be compiled with the C compiler distributed as part of the gc compiler: 6c, 8c, or 5c. It should then be combined with the compiled MODULE.go using gopack. This file will not be generated when using gccgo.

A typical command sequence would look like this:

    % swig -go example.i
    % gcc -c -fpic example.c
    % gcc -c -fpic example_wrap.c
    % gcc -shared example.o example_wrap.o -o example.so
    % 6g example.go
    % 6c example_gc.c
    % gopack grc example.a example.6 example_gc.6
    % 6g main.go  # your code, not generated by SWIG
    % 6l main.6

## 22.3 A tour of basic C/C++ wrapping

By default, SWIG attempts to build a natural Go interface to your C/C++ code. However, the languages are somewhat different, so some modifications have to occur. This section briefly covers the essential aspects of this wrapping.

### 22.3.1 Go Package Name

All Go source code lives in a package. The name of this package will default to the name of the module from SWIG's `%module` directive. You may override this by using SWIG's `-package` command line option.

### 22.3.2 Go Names

In Go, a function is only visible outside the current package if the first letter of the name is uppercase. This is quite different from C/C++. Because of this, C/C++ names are modified when generating the Go interface: the first letter is forced to be uppercase if it is not already. This affects the names of functions, methods, variables, constants, enums, and classes.

C/C++ variables are wrapped with setter and getter functions in Go. First the first letter of the variable name will be forced to uppercase, and then `Get` or `Set` will be prepended. For example, if the C/C++ variable is called `var`, then SWIG will define the functions `GetVar` and `SetVar`. If a variable is declared as `const`, or if SWIG's `%immutable` directive is used for the variable, then only the getter will be defined.

C++ classes will be discussed further below. Here we'll note that the first letter of the class name will be forced to uppercase to give the name of a type in Go. A constructor will be named `New` followed by that name, and the destructor will be named `Delete` followed by that name.

### 22.3.3 Go Constants

C/C++ constants created via `#define` or the `%constant` directive become Go constants, declared with a `const` declaration.

### 22.3.4 Go Enumerations

C/C++ enumeration types will cause SWIG to define an integer type with the name of the enumeration (with first letter forced to uppercase as usual). The values of the enumeration will become variables in Go; code should avoid modifying those variables.

### 22.3.5 Go Classes

Go has interfaces, methods and inheritance, but it does not have classes in the same sense as C++. This sections describes how SWIG represents C++ classes represented in Go.

For a C++ class `ClassName`, SWIG will define two types in Go: an underlying type, which will just hold a pointer to the C++ type, and an interface type. The interface type will be named `ClassName`. SWIG will define a function `NewClassName` which will take any constructor arguments and return a value of the interface type `ClassName`. SWIG will also define a destructor `DeleteClassName`.

SWIG will represent any methods of the C++ class as methods on the underlying type, and also as methods of the interface type. Thus C++ methods may be invoked directly using the usual `val.MethodName` syntax. Public members of the C++ class will be given getter and setter functions defined as methods of the class.

SWIG will represent static methods of C++ classes as ordinary Go functions. SWIG will use names like `ClassNameMethodName`. SWIG will give static members getter and setter functions with names like `GetClassName_VarName`.

Given a value of the interface type, Go code can retrieve the pointer to the C++ type by calling the `Swigcptr` method. This will return a value of type `SwigcptrClassName`, which is just a name for `uintptr`. A Go type conversion can be used to convert this value to a different C++ type, but note that this conversion will not be type checked and is essentially equivalent to `reinterpret_cast`. This should only be used for very special cases, such as where C++ would use a `dynamic_cast`.

Note that C++ pointers to compound objects are represented in go as objects themselves, not as go pointers. So, for example, if you wrap the following function:

    class MyClass {
      int MyMethod();
      static MyClass *MyFactoryFunction();
    };

You will get go code that looks like this:

    type MyClass interface {
      Swigcptr() uintptr
      SwigIsMyClass()
      MyMethod() int
    }

    MyClassMyFactoryFunction() MyClass {
      // swig magic here
    }

Note that the factory function does not return a go pointer; it actually returns a go interface. If the returned pointer can be null, you can check for this by calling the Swigcptr() method.

#### 22.3.5.1 Go Class Inheritance

C++ class inheritance is automatically represented in Go due to its use of interfaces. The interface for a child class will be a superset of the interface of its parent class. Thus a value of the child class type in Go may be passed to a function which expects the parent class. Doing the reverse will require an explicit type assertion, which will be checked dynamically.

### 22.3.6 Go Templates

In order to use C++ templates in Go, you must tell SWIG to create wrappers for a particular template instantation. To do this, use the `%template` directive.

### 22.3.7 Go Director Classes

SWIG's director feature permits a Go type to act as the subclass of a C++ class with virtual methods. This is complicated by the fact that C++ and Go define inheritance differently. In Go, structs can inherit methods via anonymous field embedding. However, when a method is called for an embedded struct, if that method calls any other methods, they are called for the embedded struct, not for the original type. Therefore, SWIG must use Go interfaces to represent C++ inheritance.

In order to use the director feature in Go, you must define a type in your Go code. You must then add methods for the type. Define a method in Go for each C++ virtual function that you want to override. You must then create a value of your new type, and pass a pointer to it to the function `NewDirectorClassName`, where `ClassName` is the name of the C++ class. That will return a value of type `ClassName`.

For example:

    type GoClass struct { }
    func (p *GoClass) VirtualFunction() { }
    func MakeClass() ClassName {
    	return NewDirectorClassName(&GoClass{})
    }

Any call in C++ code to the virtual function will wind up calling the method defined in Go. The Go code may of course call other methods on itself, and those methods may be defined either in Go or in C++.

### 22.3.8 Default Go primitive type mappings

The following table lists the default type mapping from C/C++ to Go. This table will tell you which Go type to expect for a function which uses a given C/C++ type.

C/C++ type | Go type
bool | bool
char | byte
signed char | int8
unsigned char | byte
short | int16
unsigned short | uint16
int | int
unsigned int | uint
long | int32 or int64, depending on `-long-type-size`
unsigned long | uint32 or uint64, depending on `-long-type-size`
long long | int64
unsigned long long | uint64
float | float32
double | float64
char * char [] | string

Note that SWIG wraps the C `char` type as a character. Pointers and arrays of this type are wrapped as strings. The `signed char` type can be used if you want to treat `char` as a signed number rather than a character. Also note that all const references to primitive types are treated as if they are passed by value.

These type mappings are defined by the "gotype" typemap. You may change that typemap, or add new values, to control how C/C++ types are mapped into Go types.

### 22.3.9 Output arguments

Because of limitations in the way output arguments are processed in swig, a function with output arguments will not have multiple return values. Instead, you must pass a pointer into the C++ function to tell it where to store the output value. In go, you supply a slice in the place of the output argument.

For example, suppose you were trying to wrap the modf() function in the C math library which splits x into integral and fractional parts (and returns the integer part in one of its parameters):

    double modf(double x, double *ip);

You could wrap it with SWIG as follows:

    %include <typemaps.i>
    double modf(double x, double *OUTPUT);

or you can use the `%apply` directive:

    %include <typemaps.i>
    %apply double *OUTPUT { double *ip };
    double modf(double x, double *ip);

In Go you would use it like this:

    ptr := []float64{0.0}
    fraction := modulename.Modf(5.0, ptr)

Since this is ugly, you may want to wrap the swig-generated API with some additional functions written in go that hide the ugly details.

There are no `char *OUTPUT` typemaps. However you can apply the `signed char *` typemaps instead:

    %include <typemaps.i>
    %apply signed char *OUTPUT {char *output};
    void f(char *output);

### 22.3.10 Adding additional go code

Often the APIs generated by swig are not very natural in go, especially if there are output arguments. You can insert additional go wrapping code to add new APIs with `%insert(go_wrapper)`, like this:

    %include <typemaps.i>
    // Change name of what swig generates to Wrapped_modf.  This function will
    // have the following signature in go:
    //   func Wrapped_modf(float64, []float64) float64
    %rename(wrapped_modf) modf(double x, double *ip);

    %apply double *OUTPUT { double *ip };
    double modf(double x, double *ip);

    %insert(go_wrapper) %{

    // The improved go interface to this function, which has two return values,
    // in the more natural go idiom:
    func Modf(x float64) (fracPart float64, intPart float64) {
      ip := []float64{0.0}
      fracPart = Wrapped_modf(x, ip)
      intPart = ip[0]
      return
    }

    %}

For classes, since swig generates an interface, you can add additional methods by defining another interface that includes the swig-generated interface. For example,

    %rename(Wrapped_MyClass) MyClass;
    %rename(Wrapped_GetAValue) MyClass::GetAValue(int *x);
    %apply int *OUTPUT { int *x };

    class MyClass {
     public:
      MyClass();
      int AFineMethod(const char *arg); // Swig's wrapping is fine for this one.
      bool GetAValue(int *x);
    };

    %insert(go_wrapper) %{

    type MyClass interface {
      Wrapped_MyClass
      GetAValue() (int, bool)
    }

    func (arg SwigcptrWrapped_MyClass) GetAValue() (int, bool) {
      ip := []int{0}
      ok := arg.Wrapped_GetAValue(ip)
      return ip[0], ok
    }

    %}

Of course, if you have to rewrite most of the methods, instead of just a few, then you might as well define your own struct that includes the swig-wrapped object, instead of adding methods to the swig-generated object.

This only works if your wrappers do not need to import other go modules. There is at present no way to insert import statements in the correct place in swig-generated go. If you need to do that, you must put your go code in a separate file.