This chapter describes SWIG's support of Go. For more information on the Go programming language see golang.org.
Go 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. The first is the gc compiler of the Go distribution, normally invoked via the go tool. The second Go compiler 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 Go compilers, selected by the -gccgo command line option.
Go is a type-safe compiled language and the wrapper code generated by SWIG is type-safe as well. In case of type issues the build will fail and hence SWIG's runtime library and runtime type checking are not used.
Working examples can be found in the SWIG source tree .
Please note that the examples in the SWIG source tree use makefiles with the .i SWIG interface file extension for backwards compatibility with Go 1.
Most Go programs are built using the go tool. Since Go 1.1 the go tool has support for SWIG. To use it, give your SWIG interface file the extension .swig (for C code) or .swigcxx (for C++ code). Put that file in a GOPATH/src directory as usual for Go sources. Put other C/C++ code in the same directory with extensions of .c and .cxx. The go build and go install commands will automatically run SWIG for you and compile the generated wrapper code. To check the SWIG command line options the go tool uses run go build -x. To access the automatically generated files run go build -work. You'll find the files under the temporary WORK directory.
To manually generate and compile C/C++ wrapper code for Go, use the -go option with SWIG. By default SWIG will generate code for the Go compiler of the Go distribution. To generate code for gccgo, you should also use the -gccgo option.
By default SWIG will generate files that can be used directly by go build. This requires Go 1.2 or later. Put your SWIG interface file in a directory under GOPATH/src, and give it a name that does not end in the .swig or .swigcxx extension. Typically the SWIG interface file extension is .i in this case.
% swig -go example.i % go install
You will now have a Go package that you can import from other Go packages as usual.
SWIG can be used without cgo, via the -no-cgo option, but more steps are required. This only works with Go versions before 1.5. When using Go version 1.2 or later, or when using gccgo, the code generated by SWIG can be linked directly into the Go program. A typical command sequence when using the Go compiler of the Go distribution would look like this:
% swig -go -no-cgo example.i % gcc -c code.c # The C library being wrapped. % gcc -c example_wrap.c % go tool 6g example.go % go tool 6c example_gc.c % go tool pack grc example.a example.6 example_gc.6 code.o example_wrap.o % go tool 6g main.go % go tool 6l main.6
You can also put the wrapped code into a shared library, and when using the Go versions before 1.2 this is the only supported option. A typical command sequence for this approach would look like this:
% swig -go -no-cgo -use-shlib example.i % gcc -c -fpic example.c % gcc -c -fpic example_wrap.c % gcc -shared example.o example_wrap.o -o example.so % go tool 6g example.go % go tool 6c example_gc.c % go tool pack grc example.a example.6 example_gc.6 % go tool 6g main.go # your code, not generated by SWIG % go tool 6l main.6
These are the command line options for SWIG's Go module. They can also be seen by using:
swig -go -help
Go-specific options | |
---|---|
-cgo | Generate files to be used as input for the Go cgo tool. This is the default. |
-no-cgo | Generate files that can be used directly, rather than via the Go cgo tool. This option does not work with Go 1.5 or later. It is required for versions of Go before 1.2. |
-intgosize <s> | Set the size for the Go type int. This controls the size that the C/C++ code expects to see. The <s> argument should be 32 or 64. This option is currently required during the transition from Go 1.0 to Go 1.1, as the size of int on 64-bit x86 systems changes between those releases (from 32 bits to 64 bits). In the future the option may become optional, and SWIG will assume that the size of int is the size of a C pointer. |
-gccgo | Generate code for gccgo. The default is to generate code for the Go compiler of the Go distribution. |
-package <name> | Set the name of the Go package to <name>. The default package name is the SWIG module name. |
-use-shlib | Tell SWIG to emit code that uses a shared library. This is only meaningful for the Go compiler of the Go distribution, which needs to know at compile time whether a shared library will be used. |
-soname <name> | 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
the Go compiler of the Go distribution; when using gccgo, the equivalent name
will be taken from the -soname option passed to the linker.
Using this option implies the -use-shlib option. |
-go-pkgpath <pkgpath> | When generating code for gccgo, set the pkgpath to use. This corresponds to the -fgo-pkgpath option to gccgo. |
-go-prefix <prefix> | When generating code for gccgo, set the prefix to use. This corresponds to the -fgo-prefix option to gccgo. If -go-pkgpath is used, -go-prefix will be ignored. |
-import-prefix <prefix> | A prefix to add when turning a %import prefix in the SWIG
interface file into an import statement in the Go file. For
example, with -import-prefix mymodule , a SWIG
interface file %import mypackage will become a Go
import statement import "mymodule/mypackage" . |
There are two different approaches to generating wrapper files, controlled by SWIG's -no-cgo option. The -no-cgo option only works with version of Go before 1.5. It is required when using versions of Go before 1.2.
With or without the -no-cgo option, SWIG will generate the following files when generating wrapper code:
When the -no-cgo option is used, and the -gccgo option is not used, SWIG will also generate an additional file:
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.
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.
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.
C/C++ constants created via #define or the %constant directive become Go constants, declared with a const declaration.
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.
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 } func 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.
Calling NewClassName for a C++ class ClassName will allocate
memory using the C++ memory allocator. This memory will not be automatically
freed by Go's garbage collector as the object ownership is not tracked. When
you are done with the C++ object you must free it using
DeleteClassName.
The most Go idiomatic way to manage the memory for some C++ class is to call
NewClassName followed by a
defer of
the DeleteClassName call. Using defer ensures that the memory
of the C++ object is freed as soon as the function containing the defer
statement returns. Furthermore defer works great for short-lived
objects and fits nicely C++'s RAII idiom. Example:
func UseClassName(...) ... { o := NewClassName(...) defer DeleteClassName(o) // Use the ClassName object return ... }
With increasing complexity, especially complex C++ object hierarchies, the correct placement of defer statements becomes harder and harder as C++ objects need to be freed in the correct order. This problem can be eased by keeping a C++ object function local so that it is only available to the function that creates a C++ object and functions called by this function. Example:
func WithClassName(constructor args, f func(ClassName, ...interface{}) error, data ...interface{}) error { o := NewClassName(constructor args) defer DeleteClassName(o) return f(o, data...) } func UseClassName(o ClassName, data ...interface{}) (err error) { // Use the ClassName object and additional data and return error. } func main() { WithClassName(constructor args, UseClassName, additional data) }
Using defer has limitations though, especially when it comes to
long-lived C++ objects whose lifetimes are hard to predict. For such C++
objects a common technique is to store the C++ object into a Go object, and to
use the Go function runtime.SetFinalizer to add a finalizer which frees
the C++ object when the Go object is freed. It is strongly recommended to read
the runtime.SetFinalizer
documentation before using this technique to understand the
runtime.SetFinalizer limitations.
Common pitfalls with runtime.SetFinalizer are:
runtime.SetFinalizer Example:
import ( "runtime" "wrap" // SWIG generated wrapper code ) type GoClassName struct { wcn wrap.ClassName } func NewGoClassName() *GoClassName { o := &GoClassName{wcn: wrap.NewClassName()} runtime.SetFinalizer(o, deleteGoClassName) return o } func deleteGoClassName(o *GoClassName) { // Runs typically in a different OS thread! wrap.DeleteClassName(o.wcn) o.wcn = nil } func (o *GoClassName) Close() { // If the C++ object has a Close method. o.wcn.Close() // If the GoClassName object is no longer in an usable state. runtime.SetFinalizer(o, nil) // Remove finalizer. deleteGoClassName() // Free the C++ object. }
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.
In order to use C++ templates in Go, you must tell SWIG to create wrappers for a particular template instantiation. To do this, use the %template directive.
SWIG's director feature permits a Go type to act as the subclass of a C++ class. This is complicated by the fact that C++ and Go define inheritance differently. SWIG normally represents the C++ class inheritance automatically in Go via interfaces but with a Go type representing a subclass of a C++ class some manual work is necessary.
This subchapter gives a step by step guide how to properly subclass a C++ class with a Go type. In general it is strongly recommended to follow this guide completely to avoid common pitfalls with directors in Go.
The step by step guide is based on two example C++ classes. FooBarAbstract is an abstract C++ class and the FooBarCpp class inherits from it. This guide explains how to implement a FooBarGo class similar to the FooBarCpp class.
FooBarAbstract abstract C++ class:
class FooBarAbstract { public: FooBarAbstract() {}; virtual ~FooBarAbstract() {}; std::string FooBar() { return this->Foo() + ", " + this->Bar(); }; protected: virtual std::string Foo() { return "Foo"; }; virtual std::string Bar() = 0; };
FooBarCpp C++ class:
class FooBarCpp : public FooBarAbstract { protected: virtual std::string Foo() { return "C++ " + FooBarAbstract::Foo(); } virtual std::string Bar() { return "C++ Bar"; } };
Returned string by the FooBarCpp::FooBar method is:
C++ Foo, C++ Bar
The complete example, including the FooBarGoo class implementation, can be found in the end of the guide.
The director feature is disabled by default. To use directors you must make two changes to the interface file. First, add the "directors" option to the %module directive, like this:
%module(directors="1") modulename
Second, you must use the %feature("director") directive to tell SWIG which classes should get directors. In the example the FooBarAbstract class needs the director feature enabled so that the FooBarGo class can inherit from it, like this:
%feature("director") FooBarAbstract;
For a more detailed documentation of the director feature and how to enable or disable it for specific classes and virtual methods see SWIG's Java documentation on directors.
SWIG creates an additional set of constructor and destructor functions once the director feature has been enabled for a C++ class. NewDirectorClassName allows overriding virtual methods on the new object instance and DeleteDirectorClassName needs to be used to free a director object instance created with NewDirectorClassName. More on overriding virtual methods follows later in this guide under overriding virtual methods.
The default constructor and destructor functions NewClassName and DeleteClassName can still be used as before so that existing code doesn't break just because the director feature has been enabled for a C++ class. The behavior is undefined if the default and director constructor and destructor functions get mixed and so great care needs to be taken that only one of the constructor and destructor function pairs is used for any object instance. Both constructor functions, the default and the director one, return the same interface type. This makes it potentially hard to know which destructor function, the default or the director one, needs to be called to delete an object instance.
In theory the DirectorInterface method could be used to determine if an object instance was created via NewDirectorClassName:
if o.DirectorInterface() != nil { DeleteDirectorClassName(o) } else { DeleteClassName(o) }
In practice it is strongly recommended to embed a director object instance in a Go struct so that a director object instance will be represented as a distinct Go type that subclasses a C++ class. For this Go type custom constructor and destructor functions take care of the director constructor and destructor function calls and the resulting Go class will appear to the user as any other SWIG wrapped C++ class. More on properly subclassing a C++ class follows later in this guide under subclass via embedding.
In order to override virtual methods on a C++ class with Go methods the NewDirectorClassName constructor functions receives a DirectorInterface argument. The methods in the DirectorInterface are a subset of the public and protected virtual methods of the C++ class. Virtual methods that have a final specifier are unsurprisingly excluded. If the DirectorInterface contains a method with a matching signature to a virtual method of the C++ class then the virtual C++ method will be overwritten with the Go method. As Go doesn't support protected methods all overridden protected virtual C++ methods will be public in Go.
As an example see part of the FooBarGo class:
type overwrittenMethodsOnFooBarAbstract struct { fb FooBarAbstract } func (om *overwrittenMethodsOnFooBarAbstract) Foo() string { ... } func (om *overwrittenMethodsOnFooBarAbstract) Bar() string { ... } func NewFooBarGo() FooBarGo { om := &overwrittenMethodsOnFooBarAbstract{} fb := NewDirectorFooBarAbstract(om) om.fb = fb ... }
The complete example, including the FooBarGoo class implementation, can be found in the end of the guide. In this part of the example the virtual methods FooBarAbstract::Foo and FooBarAbstract::Bar have been overwritten with Go methods similarly to how the FooBarAbstract virtual methods are overwritten by the FooBarCpp class.
The DirectorInterface in the example is implemented by the overwrittenMethodsOnFooBarAbstract Go struct type. A pointer to a overwrittenMethodsOnFooBarAbstract struct instance will be given to the NewDirectorFooBarAbstract constructor function. The constructor return value implements the FooBarAbstract interface. overwrittenMethodsOnFooBarAbstract could in theory be any Go type but in practice a struct is used as it typically contains at least a value of the C++ class interface so that the overwritten methods can use the rest of the C++ class. If the FooBarGo class would receive additional constructor arguments then these would also typically be stored in the overwrittenMethodsOnFooBarAbstract struct so that they can be used by the Go methods.
Often a virtual method will be overwritten to extend the original behavior of the method in the base class. This is also the case for the FooBarCpp::Foo method of the example code:
virtual std::string Foo() { return "C++ " + FooBarAbstract::Foo(); }
To use base methods the DirectorClassNameMethodName wrapper functions are automatically generated by SWIG for public and protected virtual methods. The FooBarGo.Foo implementation in the example looks like this:
func (om *overwrittenMethodsOnFooBarAbstract) Foo() string { return "Go " + DirectorFooBarAbstractFoo(om.fb) }
The complete example, including the FooBarGoo class implementation, can be found in the end of the guide.
As previously mentioned in this guide the default and director constructor functions return the same interface type. To properly subclass a C++ class with a Go type the director object instance returned by the NewDirectorClassName constructor function should be embedded into a Go struct so that it represents a distinct but compatible type in Go's type system. This Go struct should be private and the constructor and destructor functions should instead work with a public interface type so that the Go class that subclasses a C++ class can be used as a compatible drop in.
The subclassing part of the FooBarGo class for an example looks like this:
type FooBarGo interface { FooBarAbstract deleteFooBarAbstract() IsFooBarGo() } type fooBarGo struct { FooBarAbstract } func (fbgs *fooBarGo) deleteFooBarAbstract() { DeleteDirectorFooBarAbstract(fbgs.FooBarAbstract) } func (fbgs *fooBarGo) IsFooBarGo() {} func NewFooBarGo() FooBarGo { om := &overwrittenMethodsOnFooBarAbstract{} fb := NewDirectorFooBarAbstract(om) om.fb = fb return &fooBarGo{FooBarAbstract: fb} } func DeleteFooBarGo(fbg FooBarGo) { fbg.deleteFooBarAbstract() }
The complete example, including the FooBarGoo class implementation, can be found in the end of the guide. In this part of the example the private fooBarGo struct embeds FooBarAbstract which lets the fooBarGo Go type "inherit" all the methods of the FooBarAbstract C++ class by means of embedding. The public FooBarGo interface type includes the FooBarAbstract interface and hence FooBarGo can be used as a drop in replacement for FooBarAbstract while the reverse isn't possible and would raise a compile time error. Furthermore the constructor and destructor functions NewFooBarGo and DeleteFooBarGo take care of all the director specifics and to the user the class appears as any other SWIG wrapped C++ class.
In general all guidelines for C++ class memory management apply as well to director classes. One often overlooked limitation with runtime.SetFinalizer is that a finalizer doesn't run in case of a cycle and director classes typically have a cycle. The cycle in the FooBarGo class is here:
type overwrittenMethodsOnFooBarAbstract struct { fb FooBarAbstract } func NewFooBarGo() FooBarGo { om := &overwrittenMethodsOnFooBarAbstract{} fb := NewDirectorFooBarAbstract(om) // fb.v = om om.fb = fb // Backlink causes cycle as fb.v = om! ... }
In order to be able to use runtime.SetFinalizer nevertheless the finalizer needs to be set on something that isn't in a cycle and that references the director object instance. In the FooBarGo class example the FooBarAbstract director instance can be automatically deleted by setting the finalizer on fooBarGo:
type fooBarGo struct { FooBarAbstract } type overwrittenMethodsOnFooBarAbstract struct { fb FooBarAbstract } func NewFooBarGo() FooBarGo { om := &overwrittenMethodsOnFooBarAbstract{} fb := NewDirectorFooBarAbstract(om) om.fb = fb // Backlink causes cycle as fb.v = om! fbgs := &fooBarGo{FooBarAbstract: fb} runtime.SetFinalizer(fbgs, FooBarGo.deleteFooBarAbstract) return fbgs }
Furthermore if runtime.SetFinalizer is in use either the DeleteClassName destructor function needs to be removed or the fooBarGo struct needs additional data to prevent double deletion. Please read the C++ class memory management subchapter before using runtime.SetFinalizer to know all of its gotchas.
The complete and annotated FooBarGo class looks like this:
// FooBarGo is a superset of FooBarAbstract and hence FooBarGo can be used as a // drop in replacement for FooBarAbstract but the reverse causes a compile time // error. type FooBarGo interface { FooBarAbstract deleteFooBarAbstract() IsFooBarGo() } // Via embedding fooBarGo "inherits" all methods of FooBarAbstract. type fooBarGo struct { FooBarAbstract } func (fbgs *fooBarGo) deleteFooBarAbstract() { DeleteDirectorFooBarAbstract(fbgs.FooBarAbstract) } // The IsFooBarGo method ensures that FooBarGo is a superset of FooBarAbstract. // This is also how the class hierarchy gets represented by the SWIG generated // wrapper code. For an instance FooBarCpp has the IsFooBarAbstract and // IsFooBarCpp methods. func (fbgs *fooBarGo) IsFooBarGo() {} // Go type that defines the DirectorInterface. It contains the Foo and Bar // methods that overwrite the respective virtual C++ methods on FooBarAbstract. type overwrittenMethodsOnFooBarAbstract struct { // Backlink to FooBarAbstract so that the rest of the class can be used by // the overridden methods. fb FooBarAbstract // If additional constructor arguments have been given they are typically // stored here so that the overridden methods can use them. } func (om *overwrittenMethodsOnFooBarAbstract) Foo() string { // DirectorFooBarAbstractFoo calls the base method FooBarAbstract::Foo. return "Go " + DirectorFooBarAbstractFoo(om.fb) } func (om *overwrittenMethodsOnFooBarAbstract) Bar() string { return "Go Bar" } func NewFooBarGo() FooBarGo { // Instantiate FooBarAbstract with selected methods overridden. The methods // that will be overwritten are defined on // overwrittenMethodsOnFooBarAbstract and have a compatible signature to the // respective virtual C++ methods. Furthermore additional constructor // arguments will be typically stored in the // overwrittenMethodsOnFooBarAbstract struct. om := &overwrittenMethodsOnFooBarAbstract{} fb := NewDirectorFooBarAbstract(om) om.fb = fb // Backlink causes cycle as fb.v = om! fbgs := &fooBarGo{FooBarAbstract: fb} // The memory of the FooBarAbstract director object instance can be // automatically freed once the FooBarGo instance is garbage collected by // uncommenting the following line. Please make sure to understand the // runtime.SetFinalizer specific gotchas before doing this. Furthermore // DeleteFooBarGo should be deleted if a finalizer is in use or the fooBarGo // struct needs additional data to prevent double deletion. // runtime.SetFinalizer(fbgs, FooBarGo.deleteFooBarAbstract) return fbgs } // Recommended to be removed if runtime.SetFinalizer is in use. func DeleteFooBarGo(fbg FooBarGo) { fbg.deleteFooBarAbstract() }
Returned string by the FooBarGo.FooBar method is:
Go Foo, Go Bar
For comparison the FooBarCpp class looks like this:
class FooBarCpp : public FooBarAbstract { protected: virtual std::string Foo() { return "C++ " + FooBarAbstract::Foo(); } virtual std::string Bar() { return "C++ Bar"; } };
For comparison the returned string by the FooBarCpp::FooBar method is:
C++ Foo, C++ Bar
The complete source of this example can be found under SWIG/Examples/go/director/.
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 | int64 |
unsigned long | uint64 |
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.
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);
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.
If you need to import other go packages, you can do this with
%go_import
. For example,
%go_import("fmt", _ "unusedPackage", rp "renamed/package") %insert(go_wrapper) %{ func foo() { fmt.Println("Some string:", rp.GetString()) } // Importing the same package twice is permitted, // Go code will be generated with only the first instance of the import. %go_import("fmt") %insert(go_wrapper) %{ func bar() { fmt.Println("Hello world!") } %}
You can use the %typemap directive to modify SWIG's default wrapping behavior for specific C/C++ types. You need to be familiar with the material in the general "Typemaps" chapter. That chapter explains how to define a typemap. This section describes some specific typemaps used for Go.
In general type conversion code may be written either in C/C++ or in Go. The choice to make normally depends on where memory should be allocated. To allocate memory controlled by the Go garbage collector, write Go code. To allocate memory in the C/C++ heap, write C code.
Typemap | Description |
gotype | The Go type to use for a C++ type. This type will appear in the generated Go wrapper function. If this is not defined SWIG will use a default as described above. |
imtype | An intermediate Go type used by the "goin", "goout", "godirectorin", and "godirectorout" typemaps. If this typemap is not defined for a C/C++ type, the gotype typemape will be used. This is useful when gotype is best converted to C/C++ using Go code. |
goin | Go code to convert from gotype to imtype when calling a C/C++ function. SWIG will then internally convert imtype to a C/C++ type and pass it down. If this is not defined, or is the empty string, no conversion is done. |
in | C/C++ code to convert the internally generated C/C++ type, based on imtype, into the C/C++ type that a function call expects. If this is not defined the value will simply be cast to the desired type. |
out | C/C++ code to convert the C/C++ type that a function call returns into the internally generated C/C++ type, based on imtype, that will be returned to Go. If this is not defined the value will simply be cast to the desired type. |
goout | Go code to convert a value returned from a C/C++ function from imtype to gotype. If this is not defined, or is the empty string, no conversion is done. |
argout | C/C++ code to adjust an argument value when returning from a function. This is called after the real C/C++ function has run. This uses the internally generated C/C++ type, based on imtype. This is only useful for a pointer type of some sort. If this is not defined nothing will be done. |
goargout | Go code to adjust an argument value when returning from a function. This is called after the real C/C++ function has run. The value will be in imtype. This is only useful for a pointer type of some sort. If this is not defined, or is the empty string, nothing will be done. |
directorin | C/C++ code to convert the C/C++ type used to call a director method into the internally generated C/C++ type, based on imtype, that will be passed to Go. If this is not defined the value will simply be cast to the desired type. |
godirectorin | Go code to convert a value used to call a director method from imtype to gotype. If this is not defined, or is the empty string, no conversion is done. |
godirectorout | Go code to convert a value returned from a director method from gotype to imtype. If this is not defined, or is the empty string, no conversion is done. |
directorout | C/C++ code to convert a value returned from a director method from the internally generated C/C++ type, based on imtype, into the type that the method should return If this is not defined the value will simply be cast to the desired type. |