PageRenderTime 28ms CodeModel.GetById 11ms app.highlight 11ms RepoModel.GetById 2ms app.codeStats 0ms

/trunk/Doc/Manual/Go.html

#
HTML | 635 lines | 522 code | 111 blank | 2 comment | 0 complexity | e9af6e2497810b44e9104ae8fc4ac75d MD5 | raw file
  1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  2<html>
  3<head>
  4<title>SWIG and Go</title>
  5<link rel="stylesheet" type="text/css" href="style.css">
  6</head>
  7<body bgcolor="#FFFFFF">
  8<H1><a name="Go"></a>22 SWIG and Go</H1>
  9<!-- INDEX -->
 10<div class="sectiontoc">
 11<ul>
 12<li><a href="#Go_overview">Overview</a>
 13<li><a href="#Go_running_swig">Running SWIG with Go</a>
 14<ul>
 15<li><a href="#Go_commandline">Additional Commandline Options</a>
 16<li><a href="#Go_outputs">Go Output Files</a>
 17</ul>
 18<li><a href="#Go_basic_tour">A tour of basic C/C++ wrapping</a>
 19<ul>
 20<li><a href="#Go_package">Go Package Name</a>
 21<li><a href="#Go_names">Go Names</a>
 22<li><a href="#Go_constants">Go Constants</a>
 23<li><a href="#Go_enumerations">Go Enumerations</a>
 24<li><a href="#Go_classes">Go Classes</a>
 25<ul>
 26<li><a href="#Go_class_inheritance">Go Class Inheritance</a>
 27</ul>
 28<li><a href="#Go_templates">Go Templates</a>
 29<li><a href="#Go_director_classes">Go Director Classes</a>
 30<li><a href="#Go_primitive_type_mappings">Default Go primitive type mappings</a>
 31<li><a href="#Go_output_arguments">Output arguments</a>
 32<li><a href="#Go_adding_additional_code">Adding additional go code</a>
 33</ul>
 34</ul>
 35</div>
 36<!-- INDEX -->
 37
 38
 39
 40<p>
 41This chapter describes SWIG's support of Go.  For more information on
 42the Go programming language
 43see <a href="http://golang.org/">golang.org</a>.
 44</p>
 45
 46<H2><a name="Go_overview"></a>22.1 Overview</H2>
 47
 48
 49<p>
 50Go is a compiled language, not a scripting language.  However, it does
 51not support direct calling of functions written in C/C++.  The cgo
 52program may be used to generate wrappers to call C code from Go, but
 53there is no convenient way to call C++ code.  SWIG fills this gap.
 54</p>
 55
 56<p>
 57There are (at least) two different Go compilers.  One is the gc
 58compiler, normally invoked under the names 6g, 8g, or 5g.  The other
 59is the gccgo compiler, which is a frontend to the gcc compiler suite.
 60The interface to C/C++ code is completely different for the two Go
 61compilers.  SWIG supports both, selected by a command line option.
 62</p>
 63
 64<p>
 65Because Go is a type-safe compiled language, SWIG's runtime type
 66checking and runtime library are not used with Go.  This should be
 67borne in mind when reading the rest of the SWIG documentation.
 68</p>
 69
 70<H2><a name="Go_running_swig"></a>22.2 Running SWIG with Go</H2>
 71
 72
 73<p>
 74To generate Go code, use the <tt>-go</tt> option with SWIG.  By
 75default SWIG will generate code for the gc compilers.  To generate
 76code for gccgo, you should also use the <tt>-gccgo</tt> option.
 77</p>
 78
 79<H3><a name="Go_commandline"></a>22.2.1 Additional Commandline Options</H3>
 80
 81
 82<p>
 83These are the command line options for SWIG's GO module.  They can
 84also be seen by using:
 85</p>
 86
 87<div class="code"><pre>
 88swig -go -help
 89</pre></div>
 90
 91<table summary="Go specific options">
 92<tr>
 93<th>Go specific options</th>
 94</tr>
 95
 96<tr>
 97<td>-gccgo</td>
 98<td>Generate code for gccgo.  The default is to generate code for
 99  6g/8g/5g.</td>
100</tr>
101
102<tr>
103<td>-gccgo-46</td>
104<td>Generate code for gccgo 4.6.  The default is set by the configure
105  script.</td>  This generates code that does not use some facilities
106  that are only available in gccgo 4.7 and later.
107</tr>
108
109<tr>
110<td>-no-gccgo-46</td>
111<td>Turn off <code>-gccgo-46</code>, whether set by default or earlier
112  on the command line.
113</tr>
114
115<tr>
116<td>-package &lt;name&gt;</td>
117<td>Set the name of the Go package to &lt;name&gt;.  The default
118  package name is the SWIG module name.</td>
119</tr>
120
121<tr>
122<td>-soname %lt;name%gt;</td>
123<td>Set the runtime name of the shared library that the dynamic linker
124  should include at runtime.  The default is the package name with
125  ".so" appended.  This is only used when generating code for
126  6g/8g/5g; when using gccgo, the equivalent name will be taken from
127  the <code>-soname</code> option passed to the linker.</td>
128</tr>
129
130<tr>
131<td>-go-prefix &lt;prefix&gt;</td>
132<td>When generating code for gccgo, set the prefix to use.  This
133  corresponds to the <tt>-fgo-prefix</tt> option to gccgo.</td>
134</tr>
135
136<tr>
137<td>-long-type-size &lt;s&gt;</td>
138<td>Set the size for the C/C++ type <tt>long</tt>.  This controls
139  whether <tt>long</tt> is converted to the Go type <tt>int32</tt>
140  or <tt>int64</tt>.  The &lt;s&gt; argument should be 32 or 64.</td>
141</tr>
142
143</table>
144
145<H3><a name="Go_outputs"></a>22.2.2 Go Output Files</H3>
146
147
148<p> When generating Go code, SWIG will generate the following
149  files:</p>
150
151<ul>
152<li>
153MODULE.go will contain the Go functions that your Go code will call.
154These functions will be wrappers for the C++ functions defined by your
155module.  This file should, of course, be compiled with the Go
156compiler.
157<li>
158MODULE_wrap.c or MODULE_wrap.cxx will contain C/C++ functions will be
159invoked by the Go wrapper code.  This file should be compiled with the
160usual C or C++ compiler and linked into a shared library.
161<li>
162MODULE_wrap.h will be generated if you use the directors feature.  It
163provides a definition of the generated C++ director classes.  It is
164generally not necessary to use this file, but in some special cases it
165may be helpful to include it in your code, compiled with the usual C
166or C++ compiler.
167<li>
168If using the gc compiler, MODULE_gc.c will contain C code which should
169be compiled with the C compiler distributed as part of the gc compiler: 6c, 8c,
170or 5c.  It should then be combined with the compiled MODULE.go using
171gopack.  This file will not be generated when using gccgo.
172</ul>
173
174<p>
175A typical command sequence would look like this:
176</p>
177
178<div class="code"><pre>
179% swig -go example.i
180% gcc -c -fpic example.c
181% gcc -c -fpic example_wrap.c
182% gcc -shared example.o example_wrap.o -o example.so
183% 6g example.go
184% 6c example_gc.c
185% gopack grc example.a example.6 example_gc.6
186% 6g main.go  # your code, not generated by SWIG
187% 6l main.6
188</pre></div>
189
190<H2><a name="Go_basic_tour"></a>22.3 A tour of basic C/C++ wrapping</H2>
191
192
193<p>
194By default, SWIG attempts to build a natural Go interface to your
195C/C++ code.  However, the languages are somewhat different, so some
196modifications have to occur.  This section briefly covers the
197essential aspects of this wrapping.
198</p>
199
200<H3><a name="Go_package"></a>22.3.1 Go Package Name</H3>
201
202
203<p>
204All Go source code lives in a package.  The name of this package will
205default to the name of the module from SWIG's <tt>%module</tt>
206directive.  You may override this by using SWIG's <tt>-package</tt>
207command line option.
208</p>
209
210<H3><a name="Go_names"></a>22.3.2 Go Names</H3>
211
212
213<p>
214In Go, a function is only visible outside the current package if the
215first letter of the name is uppercase.  This is quite different from
216C/C++.  Because of this, C/C++ names are modified when generating the
217Go interface: the first letter is forced to be uppercase if it is not
218already.  This affects the names of functions, methods, variables,
219constants, enums, and classes.
220</p>
221
222<p>
223C/C++ variables are wrapped with setter and getter functions in Go.
224First the first letter of the variable name will be forced to
225uppercase, and then <tt>Get</tt> or <tt>Set</tt> will be prepended.
226For example, if the C/C++ variable is called <tt>var</tt>, then SWIG
227will define the functions <tt>GetVar</tt> and <tt>SetVar</tt>.  If a
228variable is declared as <tt>const</tt>, or if
229SWIG's <a href="SWIG.html#SWIG_readonly_variables">
230<tt>%immutable</tt> directive</a> is used for the variable, then only
231the getter will be defined.
232</p>
233
234<p>
235C++ classes will be discussed further below.  Here we'll note that the
236first letter of the class name will be forced to uppercase to give the
237name of a type in Go.  A constructor will be named <tt>New</tt>
238followed by that name, and the destructor will be
239named <tt>Delete</tt> followed by that name.
240</p>
241
242<H3><a name="Go_constants"></a>22.3.3 Go Constants</H3>
243
244
245<p>
246C/C++ constants created via <tt>#define</tt> or the <tt>%constant</tt>
247directive become Go constants, declared with a <tt>const</tt>
248declaration.
249
250<H3><a name="Go_enumerations"></a>22.3.4 Go Enumerations</H3>
251
252
253<p>
254C/C++ enumeration types will cause SWIG to define an integer type with
255the name of the enumeration (with first letter forced to uppercase as
256usual).  The values of the enumeration will become variables in Go;
257code should avoid modifying those variables.
258</p>
259
260<H3><a name="Go_classes"></a>22.3.5 Go Classes</H3>
261
262
263<p>
264Go has interfaces, methods and inheritance, but it does not have
265classes in the same sense as C++.  This sections describes how SWIG
266represents C++ classes represented in Go.
267</p>
268
269<p>
270For a C++ class <tt>ClassName</tt>, SWIG will define two types in Go:
271an underlying type, which will just hold a pointer to the C++ type,
272and an interface type.  The interface type will be
273named <tt>ClassName</tt>.  SWIG will define a
274function <tt>NewClassName</tt> which will take any constructor
275arguments and return a value of the interface
276type <tt>ClassName</tt>.  SWIG will also define a
277destructor <tt>DeleteClassName</tt>.
278</p>
279
280<p>
281SWIG will represent any methods of the C++ class as methods on the
282underlying type, and also as methods of the interface type.  Thus C++
283methods may be invoked directly using the
284usual <tt>val.MethodName</tt> syntax.  Public members of the C++ class
285will be given getter and setter functions defined as methods of the
286class.
287</p>
288
289<p>
290SWIG will represent static methods of C++ classes as ordinary Go
291functions.  SWIG will use names like <tt>ClassNameMethodName</tt>.
292SWIG will give static members getter and setter functions with names
293like <tt>GetClassName_VarName</tt>.
294</p>
295
296<p>
297Given a value of the interface type, Go code can retrieve the pointer
298to the C++ type by calling the <tt>Swigcptr</tt> method.  This will
299return a value of type <tt>SwigcptrClassName</tt>, which is just a
300name for <tt>uintptr</tt>.  A Go type conversion can be used to
301convert this value to a different C++ type, but note that this
302conversion will not be type checked and is essentially equivalent
303to <tt>reinterpret_cast</tt>.  This should only be used for very
304special cases, such as where C++ would use a <tt>dynamic_cast</tt>.
305</p>
306
307<p>Note that C++ pointers to compound objects are represented in go as objects
308themselves, not as go pointers.  So, for example, if you wrap the following
309function:</p>
310<div class="code">
311<pre>
312class MyClass {
313  int MyMethod();
314  static MyClass *MyFactoryFunction();
315};
316
317</pre>
318</div>
319<p>You will get go code that looks like this:</p>
320<div class="code">
321<pre>
322type MyClass interface {
323  Swigcptr() uintptr
324  SwigIsMyClass()
325  MyMethod() int
326}
327
328MyClassMyFactoryFunction() MyClass {
329  // swig magic here
330}
331</pre>
332</div>
333<p>Note that the factory function does not return a go pointer; it actually
334returns a go interface.  If the returned pointer can be null, you can check
335for this by calling the Swigcptr() method.
336</p>
337
338<H4><a name="Go_class_inheritance"></a>22.3.5.1 Go Class Inheritance</H4>
339
340
341<p>
342C++ class inheritance is automatically represented in Go due to its
343use of interfaces.  The interface for a child class will be a superset
344of the interface of its parent class.  Thus a value of the child class
345type in Go may be passed to a function which expects the parent class.
346Doing the reverse will require an explicit type assertion, which will
347be checked dynamically.
348</p>
349
350<H3><a name="Go_templates"></a>22.3.6 Go Templates</H3>
351
352
353<p>
354In order to use C++ templates in Go, you must tell SWIG to create
355wrappers for a particular template instantation.  To do this, use
356the <tt>%template</tt> directive.
357
358<H3><a name="Go_director_classes"></a>22.3.7 Go Director Classes</H3>
359
360
361<p>
362SWIG's director feature permits a Go type to act as the subclass of a
363C++ class with virtual methods.  This is complicated by the fact that
364C++ and Go define inheritance differently.  In Go, structs can inherit
365methods via anonymous field embedding.  However, when a method is
366called for an embedded struct, if that method calls any other methods,
367they are called for the embedded struct, not for the original type.
368Therefore, SWIG must use Go interfaces to represent C++ inheritance.
369</p>
370
371<p>
372In order to use the director feature in Go, you must define a type in
373your Go code.  You must then add methods for the type.  Define a
374method in Go for each C++ virtual function that you want to override.
375You must then create a value of your new type, and pass a pointer to
376it to the function <tt>NewDirectorClassName</tt>,
377where <tt>ClassName</tt> is the name of the C++ class.  That will
378return a value of type <tt>ClassName</tt>.
379</p>
380
381<p>
382For example:
383</p>
384
385<div class="code">
386<pre>
387type GoClass struct { }
388func (p *GoClass) VirtualFunction() { }
389func MakeClass() ClassName {
390	return NewDirectorClassName(&amp;GoClass{})
391}
392</pre>
393</div>
394
395<p>
396Any call in C++ code to the virtual function will wind up calling the
397method defined in Go.  The Go code may of course call other methods on
398itself, and those methods may be defined either in Go or in C++.
399</p>
400
401<H3><a name="Go_primitive_type_mappings"></a>22.3.8 Default Go primitive type mappings</H3>
402
403
404<p>
405The following table lists the default type mapping from C/C++ to Go.
406This table will tell you which Go type to expect for a function which
407uses a given C/C++ type.
408</p>
409
410<table BORDER summary="Go primitive type mappings">
411<tr>
412<td><b>C/C++ type</b></td>
413<td><b>Go type</b></td>
414</tr>
415
416<tr>
417<td>bool</td>
418<td>bool</td>
419</tr>
420
421<tr>
422<td>char</td>
423<td>byte</td>
424</tr>
425
426<tr>
427<td>signed char</td>
428<td>int8</td>
429</tr>
430
431<tr>
432<td>unsigned char</td>
433<td>byte</td>
434</tr>
435
436<tr>
437<td>short</td>
438<td>int16</td>
439</tr>
440
441<tr>
442<td>unsigned short</td>
443<td>uint16</td>
444</tr>
445
446<tr>
447<td>int</td>
448<td>int</td>
449</tr>
450
451<tr>
452<td>unsigned int</td>
453<td>uint</td>
454</tr>
455
456<tr>
457<td>long</td>
458<td>int32 or int64, depending on <tt>-long-type-size</tt></td>
459</tr>
460
461<tr>
462<td>unsigned long</td>
463<td>uint32 or uint64, depending on <tt>-long-type-size</tt></td>
464</tr>
465
466<tr>
467<td>long long</td>
468<td>int64</td>
469</tr>
470
471<tr>
472<td>unsigned long long</td>
473<td>uint64</td>
474</tr>
475
476<tr>
477<td>float</td>
478<td>float32</td>
479</tr>
480
481<tr>
482<td>double</td>
483<td>float64</td>
484</tr>
485
486<tr>
487<td>char *<br>char []</td>
488<td>string</td>
489</tr>
490
491</table>
492
493<p>
494Note that SWIG wraps the C <tt>char</tt> type as a character. Pointers
495and arrays of this type are wrapped as strings.  The <tt>signed
496char</tt> type can be used if you want to treat <tt>char</tt> as a
497signed number rather than a character.  Also note that all const
498references to primitive types are treated as if they are passed by
499value.
500</p>
501
502<p>
503These type mappings are defined by the "gotype" typemap.  You may change
504that typemap, or add new values, to control how C/C++ types are mapped
505into Go types.
506</p>
507
508<H3><a name="Go_output_arguments"></a>22.3.9 Output arguments</H3>
509
510
511<p>Because of limitations in the way output arguments are processed in swig,
512a function with output arguments will not have multiple return values.
513Instead, you must pass a pointer into the C++ function to tell it where to
514store the ouput value.  In go, you supply a slice in the place of the output
515argument.</p>
516
517<p>For example, suppose you were trying to wrap the modf() function in the
518C math library which splits x into integral and fractional parts (and
519returns the integer part in one of its parameters):</p>
520<div class="code">
521<pre>
522double modf(double x, double *ip);
523</pre>
524</div>
525<p>You could wrap it with SWIG as follows:</p>
526<div class="code">
527<pre>
528%include &lt;typemaps.i&gt;
529double modf(double x, double *OUTPUT);
530</pre>
531</div>
532<p>or you can use the <code>%apply</code> directive:</p>
533<div class="code">
534<pre>
535%include &lt;typemaps.i&gt;
536%apply double *OUTPUT { double *ip };
537double modf(double x, double *ip);
538</pre>
539</div>
540<p>In Go you would use it like this:</p>
541<div class="code">
542<pre>
543ptr := []float64{0.0}
544fraction := modulename.Modf(5.0, ptr)
545</pre>
546</div>
547<p>Since this is ugly, you may want to wrap the swig-generated API with
548some <a href="#Embedded_go_code">additional functions written in go</a> that
549hide the ugly details.</p>
550
551<p>There are no <code>char&nbsp;*OUTPUT</code> typemaps.  However you can
552apply the <code>signed&nbsp;char&nbsp;*</code> typemaps instead:</p>
553<div class="code">
554<pre>
555%include &lt;typemaps.i&gt;
556%apply signed char *OUTPUT {char *output};
557void f(char *output);
558</pre>
559</div>
560
561<H3><a name="Go_adding_additional_code"></a>22.3.10 Adding additional go code</H3>
562
563
564<p>Often the APIs generated by swig are not very natural in go, especially if
565there are output arguments.  You can
566insert additional go wrapping code to add new APIs
567with <code>%insert(go_wrapper)</code>, like this:</p>
568<div class="code">
569<pre>
570%include &lt;typemaps.i&gt;
571// Change name of what swig generates to Wrapped_modf.  This function will
572// have the following signature in go:
573//   func Wrapped_modf(float64, []float64) float64
574%rename(wrapped_modf) modf(double x, double *ip);
575
576%apply double *OUTPUT { double *ip };
577double modf(double x, double *ip);
578
579%insert(go_wrapper) %{
580
581// The improved go interface to this function, which has two return values,
582// in the more natural go idiom:
583func Modf(x float64) (fracPart float64, intPart float64) {
584  ip := []float64{0.0}
585  fracPart = Wrapped_modf(x, ip)
586  intPart = ip[0]
587  return
588}
589
590%}
591</pre>
592</div>
593
594<p>For classes, since swig generates an interface, you can add additional
595methods by defining another interface that includes the swig-generated
596interface.  For example,</p>
597<div class="code">
598<pre>
599%rename(Wrapped_MyClass) MyClass;
600%rename(Wrapped_GetAValue) MyClass::GetAValue(int *x);
601%apply int *OUTPUT { int *x };
602
603class MyClass {
604 public:
605  MyClass();
606  int AFineMethod(const char *arg); // Swig's wrapping is fine for this one.
607  bool GetAValue(int *x);
608};
609
610%insert(go_wrapper) %{
611
612type MyClass interface {
613  Wrapped_MyClass
614  GetAValue() (int, bool)
615}
616
617func (arg SwigcptrWrapped_MyClass) GetAValue() (int, bool) {
618  ip := []int{0}
619  ok := arg.Wrapped_GetAValue(ip)
620  return ip[0], ok
621}
622
623%}
624</pre>
625</div>
626<p>Of course, if you have to rewrite most of the methods, instead of just a
627few, then you might as well define your own struct that includes the
628swig-wrapped object, instead of adding methods to the swig-generated object.</p>
629
630<p>This only works if your wrappers do not need to import other go modules.
631There is at present no way to insert import statements in the correct place
632in swig-generated go.  If you need to do that, you must put your go code
633in a separate file.</p>
634</body>
635</html>