# 17 SWIG and C#

- Introduction
- Differences to the Java module
- C# Exceptions
  - C# exception example using "check" typemap
  - C# exception example using %exception
  - C# exception example using exception specifications
  - Custom C# ApplicationException example
- C# Typemap examples
  - Memory management when returning references to member variables
  - Memory management for objects passed to the C++ layer

## 17.1 Introduction

The purpose of the C# module is to offer an automated way of accessing existing C/C++ code from .NET languages. The wrapper code implementation uses C# and the Platform Invoke (PInvoke) interface to access natively compiled C/C++ code. The PInvoke interface has been chosen over Microsoft's Managed C++ interface as it is portable to both Microsoft Windows and non-Microsoft platforms. PInvoke is part of the ECMA/ISO C# specification. It is also better suited for robust production environments due to the Managed C++ flaw called the Mixed DLL Loading Problem. Swig C# works equally well on non-Microsoft operating systems such as Linux, Solaris and Apple Mac using Mono and Portable.NET.

To get the most out of this chapter an understanding of interop is required. The Microsoft Developer Network (MSDN) has a good reference guide in a section titled "Interop Marshaling". Monodoc, available from the Mono project, has a very useful section titled Interop with native libraries.

## 17.2 Differences to the Java module

The C# module is very similar to the Java module, so until some more complete documentation has been written, please use the Java documentation as a guide to using SWIG with C#. The rest of this section should be read in conjunction with the Java documentation as it lists the main differences.

Director support (virtual method callbacks into C#) has not yet been implemented and is the main missing feature compared to Java. Less of the STL is supported and there are also a few minor utility typemaps in the various.i library which are missing.

The most noteable differences to Java are the following:

- When invoking SWIG use the `-csharp` command line option instead of `-java`.
- The `-package` command line option does not exist.
- The `-namespace <name>` commandline option will generate all code into the namespace specified by `<name>`.
- The `-dllimport <name>` commandline option specifies the name of the DLL for the `DllImport` attribute for every PInvoke method. If this commandline option is not given, the `DllImport` DLL name is the same as the module name. This option is useful for when one wants to invoke SWIG multiple times on different modules, yet compile all the resulting code into a single DLL.
- C/C++ variables are wrapped with C# properties and not JavaBean style getters and setters.
- Global constants are generated into the module class. There is no constants interface.
- There is no implementation for type unsafe enums - not deemed necessary.
- The default enum wrapping approach is proper C# enums, not typesafe enums.
  Note that %csconst(0) will be ignored when wrapping C/C++ enums with proper C# enums. This is because C# enum items must be initialised from a compile time constant. If an enum item has an initialiser and the initialiser doesn't compile as C# code, then the %csconstvalue directive must be used as %csconst(0) will have no effect. If it was used, it would generate an illegal runtime initialisation via a PInvoke call.
- C# doesn't support the notion of throws clauses. Therefore there is no 'throws' typemap attribute support for adding exception classes to a throws clause. Likewise there is no need for an equivalent to `%javaexception`. In fact, throwing C# exceptions works quite differently, see C# Exceptions> below.
- The majority of the typemaps are in csharp.swg, not java.swg.

- Typemap equivalent names:

      jni                         -> ctype
      jtype                       -> imtype
      jstype                      -> cstype
      javain                      -> csin
      javaout                     -> csout
      javainterfaces              -> csinterfaces and csinterfaces_derived
      javabase                    -> csbase
      javaclassmodifiers          -> csclassmodifiers
      javacode                    -> cscode
      javaimports                 -> csimports
      javabody                    -> csbody
      javafinalize                -> csfinalize
      javadestruct                -> csdestruct
      javadestruct_derived        -> csdestruct_derived

- Additional typemaps:

      csvarin                     C# code property set typemap
      csvarout                    C# code property get typemap
      csattributes                C# attributes for attaching to proxy classes/enums

- Feature equivalent names:

      %javaconst                  -> %csconst
      %javaconstvalue             -> %csconstvalue
      %javamethodmodifiers        -> %csmethodmodifiers

- Pragma equivalent names:

      %pragma(java)               -> %pragma(csharp)
      jniclassbase                -> imclassbase
      jniclassclassmodifiers      -> imclassclassmodifiers
      jniclasscode                -> imclasscode
      jniclassimports             -> imclassimports
      jniclassinterfaces          -> imclassinterfaces

- Special variable equivalent names:

      $javaclassname              -> $csclassname
      $javainput                  -> $csinput
      $jnicall                    -> $imcall

- The intermediary classname has `PINVOKE` appended after the module name instead of `JNI`, for example `modulenamePINVOKE`.

- Support for asymmetric type marshalling. The 'ctype', 'imtype' and 'cstype' typemaps support an optional `out` attribute which is used for output types. If this typemap attribute is specified, then the type specified in the attribute is used for output types and the type specified in the typemap itself is used for the input type. If this typemap attribute is not specified, then the type used for both input and output is the type specified in the typemap. An example shows that `char *` could be marshalled in different ways,

      %typemap(imtype, out="IntPtr") char * "string"
      char * function(char *);

  The output type is thus IntPtr and the input type is string. The resulting intermediary C# code is:

      public static extern IntPtr function(string jarg1);

- Support for type attributes. The 'imtype' and 'cstype' typemaps can have an optional `inattributes` and `outattributes` typemap attribute. There are C# attributes and typemap attributes, don't get confused!! The C# attributes specified in these typemap attributes are generated wherever the type is used in the C# wrappers. These can be used to specify any C# attribute associated with a C/C++ type, but are more typically used for the C# `MarshalAs` attribute. For example:

      %typemap(imtype,
               inattributes="[MarshalAs(UnmanagedType.LPStr)]",
               outattributes="[return: MarshalAs(UnmanagedType.LPStr)]") const char * "String"

      const char * GetMsg() {}
      void SetMsg(const char *msg) {}

  The intermediary class will then have the marshalling as specified by everything in the 'imtype' typemap:

      class examplePINVOKE {
        ...
        [DllImport("example", EntryPoint="CSharp_GetMsg")]
        [return: MarshalAs(UnmanagedType.LPStr)]
        public static extern String GetMsg();

        [DllImport("example", EntryPoint="CSharp_SetMsg")]
        public static extern void SetMsg([MarshalAs(UnmanagedType.LPStr)]String jarg1);
      }

  Note that the `DllImport` attribute is always generated, irrespective of any additional attributes specified.

  These attributes are associated with the C/C++ parameter type or return type, which is subtely different to the attribute features and typemaps covered next. Note that all these different C# attributes can be combined so that a method has more than one attribute.

- Support for attaching C# attributes to wrapped methods and variables. This is done using the `%csattributes` feature, see %feature directives. Note that C# attributes are attached to proxy classes and enums using the `csattributes` typemap. For example, imagine we have a custom attribute class, `ThreadSafeAttribute`, for labelling thread safety. The following SWIG code shows how to attach this C# attribute to some methods and the class declaration itself:

      %typemap(csattributes) AClass          "[ThreadSafe]"
      %csattributes AClass::AClass(double d) "[ThreadSafe(false)]"
      %csattributes AClass::AMethod()        "[ThreadSafe(true)]"

      %inline %{
      class AClass {
      public:
        AClass(double a) {}
        void AMethod() {}
      };
      %}

  will generate a C# proxy class:

      [ThreadSafe]
      public class AClass : IDisposable {
        ...
        [ThreadSafe(false)]
        public AClass(double a) ...

        [ThreadSafe(true)]
        public void AMethod() ...
      }

  If C# attributes need adding to the `set` or `get` part of C# properties, when wrapping C/C++ variables, they can be added using the 'csvarin' and 'csvarout' typemaps respectively.

- The `%csmethodmodifiers` feature can also be applied to variables as well as methods. In addition to the default `public` modifier that SWIG generates when `%csmethodmodifiers` is not specified, the feature will also replace the `virtual`/`new`/`override` modifiers that SWIG thinks is appropriate. This feature is useful for some obscure cases where SWIG might get the `virtual`/`new`/`override` modifiers incorrect, for example with multiple inheritance.

- The name of the intermediary class can be changed from its default, that is, the module name with PINVOKE appended after it. The module directive attribute `imclassname` is used to achieve this:

      %module (imclassname="name") modulename

  If `name` is the same as `modulename` then the module class name gets changed from `modulename` to `modulenameModule`.

`$dllimport`
This is a C# only special variable that can be used in typemaps, pragmas, features etc. The special variable will get translated into the value specified by the `-dllimport` commandline option if specified, otherwise it is equivalent to the $module special variable.

`$imclassname`
This special variable expands to the intermediary class name. For C# this is usually the same as '$modulePINVOKE' ('$moduleJNI' for Java), unless the imclassname attribute is specified in the %module directive.

The directory `Examples/csharp` has a number of simple examples. Visual Studio .NET 2003 solution and project files are available for compiling with the Microsoft .NET C# compiler on Windows. If your SWIG installation went well on a Unix environment and your C# compiler was detected, you should be able to type `make` in each example directory, then `ilrun runme.exe` (Portable.NET C# compiler) or `mono runme.exe` (Mono C# compiler) to run the examples. Windows users can also get the examples working using a Cygwin or MinGW environment for automatic configuration of the example makefiles. Any one of the three C# compilers (Portable.NET, Mono or Microsoft) can be detected from within a Cygwin or Mingw environment if installed in your path.

## 17.3 C# Exceptions

It is possible to throw a C# Exception from C/C++ code. SWIG already provides the framework for throwing C# exceptions if it is able to detect that a C++ exception could be thrown. Automatically detecting that a C++ exception could be thrown is only possible when a C++ exception specification is used, see Exception specifications. The Exception handling with %exception section details the `%exception` feature. Customised code for handling exceptions with or without a C++ exception specification is possible and the details follow. However anyone wishing to do this should be familiar with the contents of the sections referred to above.

Unfortunately a C# exception cannot simply be thrown from unmanaged code for a variety of reasons. Most noteably being that throwing a C# exception results in exceptions being thrown across the C PInvoke interface and C does not understand exceptions. The design revolves around a C# exception being constructed and stored as a pending exception, to be thrown only when the unmanaged code has completed. Implementing this is a tad involved and there are thus some unusual typemap constructs. Some practical examples follow and they should be read in conjunction with the rest of this section.

First some details about the design that must be followed. Each typemap or feature that generates unmanaged code supports an attribute called `canthrow`. This is simply a flag which when set indicates that the code in the typemap/feature has code which might want to throw a C# exception. The code in the typemap/feature can then raise a C# exception by calling one of the C functions, `SWIG_CSharpSetPendingException()` or `SWIG_CSharpSetPendingExceptionArgument()`. When called, the function makes a callback into the managed world via a delegate. The callback creates and stores an exception ready for throwing when the unmanaged code has finished. The typemap/feature unmanaged code is then expected to force an immediate return from the unmanaged wrapper function, so that the pending managed exception can then be thrown. The support code has been carefully designed to be efficient as well as thread-safe. However to achieve the goal of efficiency requires some optional code generation in the managed code typemaps. Code to check for pending exceptions is generated if and only if the unmanaged code has code to set a pending exception, that is if the `canthrow` attribute is set. The optional managed code is generated using the `excode` typemap attribute and `$excode` special variable in the relevant managed code typemaps. Simply, if any relevant unmanaged code has the `canthrow` attribute set, then any occurrences of `$excode` is replaced with the code in the `excode` attribute. If the `canthrow` attribute is not set, then any occurrences of `$excode` are replaced with nothing.

The prototypes for the `SWIG_CSharpSetPendingException()` and `SWIG_CSharpSetPendingExceptionArgument()` functions are

    static void SWIG_CSharpSetPendingException(SWIG_CSharpExceptionCodes code,
                                               const char *msg);

    static void SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpExceptionArgumentCodes code,
                                                       const char *msg,
                                                       const char *param_name);

The first parameter defines which .NET exceptions can be thrown:

    typedef enum {
      SWIG_CSharpApplicationException,
      SWIG_CSharpArithmeticException,
      SWIG_CSharpDivideByZeroException,
      SWIG_CSharpIndexOutOfRangeException,
      SWIG_CSharpInvalidOperationException,
      SWIG_CSharpIOException,
      SWIG_CSharpNullReferenceException,
      SWIG_CSharpOutOfMemoryException,
      SWIG_CSharpOverflowException,
      SWIG_CSharpSystemException
    } SWIG_CSharpExceptionCodes;

    typedef enum {
      SWIG_CSharpArgumentException,
      SWIG_CSharpArgumentNullException,
      SWIG_CSharpArgumentOutOfRangeException,
    } SWIG_CSharpExceptionArgumentCodes;

where, for example, `SWIG_CSharpApplicationException` corresponds to the .NET exception, `ApplicationException`. The `msg` and `param_name` parameters contain the C# exception message and parameter name associated with the exception.

The `%exception` feature in C# has the `canthrow` attribute set. The `%csnothrowexception` feature is like `%exception`, but it does not have the `canthrow` attribute set so should only be used when a C# exception is not created.

### 17.3.1 C# exception example using "check" typemap

Lets say we have the following simple C++ method:

    void positivesonly(int number);

and we want to check that the input `number` is always positive and if not throw a C# `ArgumentOutOfRangeException`. The "check" typemap is designed for checking input parameters. Below you will see the `canthrow` attribute is set because the code contains a call to `SWIG_CSharpSetPendingExceptionArgument()`. The full example follows:

    %module example

    %typemap(check, canthrow=1) int number %{
    if ($1 < 0) {
      SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
                                             "only positive numbers accepted", "number");
      return $null;
    }
    // SWIGEXCODE is a macro used by many other csout typemaps
    %define SWIGEXCODE
     "\n    if ($modulePINVOKE.SWIGPendingException.Pending)"
     "\n      throw $modulePINVOKE.SWIGPendingException.Retrieve();"
    %enddef
    %typemap(csout, excode=SWIGEXCODE) void {
        $imcall;$excode
      }
    %}

    %inline %{

    void positivesonly(int number) {
    }

    %}

When the following C# code is executed:

    public class runme {
        static void Main() {
          example.positivesonly(-1);
        }
    }

The exception is thrown:

    Unhandled Exception: System.ArgumentOutOfRangeException: only positive numbers accepted
    Parameter name: number
    in <0x00034> example:positivesonly (int)
    in <0x0000c> runme:Main ()

Now let's analyse the generated code to gain a fuller understanding of the typemaps. The generated unmanaged C++ code is:

    SWIGEXPORT void SWIGSTDCALL CSharp_positivesonly(int jarg1) {
        int arg1 ;

        arg1 = (int)jarg1;

        if (arg1 < 0) {
            SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
                                                   "only positive numbers accepted", "number");
            return ;
        }

        positivesonly(arg1);

    }

This largely comes from the "check" typemap. The managed code in the module class is:

    public class example {
      public static void positivesonly(int number) {
        examplePINVOKE.positivesonly(number);
        if (examplePINVOKE.SWIGPendingException.Pending)
          throw examplePINVOKE.SWIGPendingException.Retrieve();
      }

    }

This comes largely from the "csout" typemap.

The "csout" typemap is the same as the default void "csout" typemap so is not strictly necessary for the example. However, it is shown to demonstrate what managed output code typemaps should contain, that is, a `$excode` special variable and an `excode` attribute. Also note that `$excode` is expanded into the code held in the `excode` attribute. The `$imcall` as always expands into `examplePINVOKE.positivesonly(number)`. The exception support code in the intermediary class, `examplePINVOKE`, is not shown, but is contained within the inner classes, `SWIGPendingException` and `SWIGExceptionHelper` and is always generated. These classes can be seen in any of the generated wrappers. However, all that is required of a user is as demonstrated in the "csin" typemap above. That is, is to check `SWIGPendingException.Pending` and to throw the exception returned by `SWIGPendingException.Retrieve()`.

If the "check" typemap did not exist, then the following module class would instead be generated:

    public class example {
      public static void positivesonly(int number) {
        examplePINVOKE.positivesonly(number);
      }

    }

Here we see the pending exception checking code is omitted. In fact, the code above would be generated if the `canthrow` attribute was not in the "check" typemap, such as:

    %typemap(check) int number %{
    if ($1 < 0) {
      SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
                                             "only positive numbers accepted", "number");
      return $null;
    }
    %}

Note that if SWIG detects you have used `SWIG_CSharpSetPendingException()` or `SWIG_CSharpSetPendingExceptionArgument()` without setting the `canthrow` attribute you will get a warning message similar to

    example.i:21: Warning(845): Unmanaged code contains a call to a SWIG_CSharpSetPendingException
    method and C# code does not handle pending exceptions via the canthrow attribute.

Actually it will issue this warning for any function beginning with `SWIG_CSharpSetPendingException`.

### 17.3.2 C# exception example using %exception

Let's consider a similar, but more common example that throws a C++ exception from within a wrapped function. We can use `%exception` as mentioned in Exception handling with %exception.

    %exception negativesonly(int value) %{
    try {
      $action
    } catch (std::out_of_range e) {
      SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
    }
    %}

    %inline %{
    #include <stdexcept>
    void negativesonly(int value) {
      if (value >= 0)
        throw std::out_of_range("number should be negative");
    }
    %}

The generated unmanaged code this time catches the C++ exception and converts it into a C# `ApplicationException`.

    SWIGEXPORT void SWIGSTDCALL CSharp_negativesonly(int jarg1) {
        int arg1 ;

        arg1 = (int)jarg1;

        try {
            negativesonly(arg1);

        } catch (std::out_of_range e) {
            SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
            return ;
        }

    }

The managed code generated does check for the pending exception as mentioned earlier as the C# version of `%exception` has the `canthrow` attribute set by default:

      public static void negativesonly(int value) {
        examplePINVOKE.negativesonly(value);
        if (examplePINVOKE.SWIGPendingException.Pending)
          throw examplePINVOKE.SWIGPendingException.Retrieve();
      }

### 17.3.3 C# exception example using exception specifications

When C++ exception specifications are used, SWIG is able to detect that the method might throw an exception. By default SWIG will automatically generate code to catch the exception and convert it into a managed `ApplicationException`, as defined by the default "throws" typemaps. The following example has a user supplied "throws" typemap which is used whenever an exception specification contains a `std::out_of_range`, such as the `evensonly` method below.

    %typemap(throws, canthrow=1) std::out_of_range {
      SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, $1.what(), NULL);
      return $null;
    }

    %inline %{
    #include <stdexcept>
    void evensonly(int input) throw (std::out_of_range) {
      if (input%2 != 0)
        throw std::out_of_range("number is not even");
    }
    %}

Note that the type for the throws typemap is the type in the exception specification. SWIG generates a try catch block with the throws typemap code in the catch handler.

    SWIGEXPORT void SWIGSTDCALL CSharp_evensonly(int jarg1) {
        int arg1 ;

        arg1 = (int)jarg1;
        try {
            evensonly(arg1);
        }
        catch(std::out_of_range &_e) {
          {
              SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, (&_e)->what(), NULL);
              return ;
          }
        }

    }

Multiple catch handlers are generated should there be more than one exception specifications declared.

### 17.3.4 Custom C# ApplicationException example

This example involves a user defined exception. The conventional .NET exception handling approach is to create a custom `ApplicationException` and throw it in your application. The goal in this example is to convert the STL `std::out_of_range` exception into one of these custom .NET exceptions.

The default exception handling is quite easy to use as the `SWIG_CSharpSetPendingException()` and `SWIG_CSharpSetPendingExceptionArgument()` methods are provided by SWIG. However, for a custom C# exception, the boiler plate code that supports these functions needs replicating. In essence this consists of some C/C++ code and C# code. The C/C++ code can be generated into the wrapper file using the `%insert(runtime)` directive and the C# code can be generated into the intermediary class using the `imclasscode` pragma as follows:

    %insert(runtime) %{
      // Code to handle throwing of C# CustomApplicationException from C/C++ code.
      // The equivalent delegate to the callback, CSharpExceptionCallback_t, is CustomExceptionDelegate
      // and the equivalent customExceptionCallback instance is customDelegate
      typedef void (SWIGSTDCALL* CSharpExceptionCallback_t)(const char *);
      CSharpExceptionCallback_t customExceptionCallback = NULL;

      extern "C" SWIGEXPORT
      void SWIGSTDCALL CustomExceptionRegisterCallback(CSharpExceptionCallback_t customCallback) {
        customExceptionCallback = customCallback;
      }

      // Note that SWIG detects any method calls named starting with
      // SWIG_CSharpSetPendingException for warning 845
      static void SWIG_CSharpSetPendingExceptionCustom(const char *msg) {
        customExceptionCallback(msg);
      }
    %}

    %pragma(csharp) imclasscode=%{
      class CustomExceptionHelper {
        // C# delegate for the C/C++ customExceptionCallback
        public delegate void CustomExceptionDelegate(string message);
        static CustomExceptionDelegate customDelegate =
                                       new CustomExceptionDelegate(SetPendingCustomException);

        [DllImport("$dllimport", EntryPoint="CustomExceptionRegisterCallback")]
        public static extern
               void CustomExceptionRegisterCallback(CustomExceptionDelegate customCallback);

        static void SetPendingCustomException(string message) {
          SWIGPendingException.Set(new CustomApplicationException(message));
        }

        static CustomExceptionHelper() {
          CustomExceptionRegisterCallback(customDelegate);
        }
      }
      static CustomExceptionHelper exceptionHelper = new CustomExceptionHelper();
    %}

The method stored in the C# delegate instance, `customDelegate` is what gets called by the C/C++ callback. However, the equivalent to the C# delegate, that is the C/C++ callback, needs to be assigned before any unmanaged code is executed. This is achieved by putting the initialisation code in the intermediary class. Recall that the intermediary class contains all the PInvoke methods, so the static variables in the intermediary class will be initialised before any of the PInvoke methods in this class are called. The `exceptionHelper` static variable ensures the C/C++ callback is initialised with the value in `customDelegate` by calling the `CustomExceptionRegisterCallback` method in the `CustomExceptionHelper` static constructor. Once this has been done, unmanaged code can make callbacks into the managed world as `customExceptionCallback` will be initialised with a valid callback/delegate. Any calls to `SWIG_CSharpSetPendingExceptionCustom()` will make the callback to create the pending exception in the same way that `SWIG_CSharpSetPendingException()` and `SWIG_CSharpSetPendingExceptionArgument()` does. In fact the method has been similarly named so that SWIG can issue the warning about missing `canthrow` attributes as discussed earlier. It is an invaluable warning as it is easy to forget the `canthrow` attribute when writing typemaps/features.

The `SWIGPendingException` helper class is not shown, but is generated as an inner class into the intermediary class. It stores the pending exception in Thread Local Storage so that the exception handling mechanism is thread safe.

The boiler plate code above must be used in addition to a handcrafted `CustomApplicationException`:

    // Custom C# Exception
    class CustomApplicationException : System.ApplicationException {
      public CustomApplicationException(string message)
        : base(message) {
      }
    }

and the SWIG interface code:

    %typemap(throws, canthrow=1) std::out_of_range {
      SWIG_CSharpSetPendingExceptionCustom($1.what());
      return $null;
    }

    %inline %{
    void oddsonly(int input) throw (std::out_of_range) {
      if (input%2 != 1)
        throw std::out_of_range("number is not odd");
    }
    %}

The "throws" typemap now simply calls our new `SWIG_CSharpSetPendingExceptionCustom()` function so that the exception can be caught, as such:

    try {
      example.oddsonly(2);
    } catch (CustomApplicationException e) {
      ...
    }

## 17.4 C# Typemap examples

This section includes a few examples of typemaps. For more examples, you might look at the files "`csharp.swg`" and "`typemaps.i`" in the SWIG library.

### 17.4.1 Memory management when returning references to member variables

This example shows how to prevent early garbage collection of objects when the underlying C++ class returns a pointer or reference to a member variable. The example is a direct equivalent to this Java equivalent.

Consider the following C++ code:

    struct Wheel {
      int size;
      Wheel(int sz) : size(sz) {}
    };

    class Bike {
      Wheel wheel;
    public:
      Bike(int val) : wheel(val) {}
      Wheel& getWheel() { return wheel; }
    };

and the following usage from C# after running the code through SWIG:

          Wheel wheel = new Bike(10).getWheel();
          Console.WriteLine("wheel size: " + wheel.size);
          // Simulate a garbage collection
          System.GC.Collect();
          System.GC.WaitForPendingFinalizers();
          Console.WriteLine("wheel size: " + wheel.size);

Don't be surprised that if the resulting output gives strange results such as...

    wheel size: 10
    wheel size: 135019664

What has happened here is the garbage collector has collected the `Bike` instance as it doesn't think it is needed any more. The proxy instance, `wheel`, contains a reference to memory that was deleted when the `Bike` instance was collected. In order to prevent the garbage collector from collecting the `Bike` instance a reference to the `Bike` must be added to the `wheel` instance. You can do this by adding the reference when the `getWheel()` method is called using the following typemaps.

    %typemap(cscode) Wheel %{
      // Ensure that the GC doesn't collect any Bike instance set from C#
      private Bike bikeReference;
      internal void addReference(Bike bike) {
        bikeReference = bike;
      }
    %}

    // Add a C# reference to prevent early garbage collection and resulting use
    // of dangling C++ pointer. Intended for methods that return pointers or
    // references to a member variable.
    %typemap(csout, excode=SWIGEXCODE) Wheel& getWheel {
        IntPtr cPtr = $imcall;$excode
        $csclassname ret = null;
        if (cPtr != IntPtr.Zero) {
          ret = new $csclassname(cPtr, $owner);
          ret.addReference(this);
        }
        return ret;
      }

The code in the first typemap gets added to the `Wheel` proxy class. The code in the second typemap constitutes the bulk of the code in the generated `getWheel()` function:

    public class Wheel : IDisposable {
      ...
      // Ensure that the GC doesn't collect any Bike instance set from C#
      private Bike bikeReference;
      internal void addReference(Bike bike) {
        bikeReference = bike;
      }
    }

    public class Bike : IDisposable {
      ...
      public Wheel getWheel() {
        IntPtr cPtr = examplePINVOKE.Bike_getWheel(swigCPtr);
        Wheel ret = null;
        if (cPtr != IntPtr.Zero) {
          ret = new Wheel(cPtr, false);
          ret.addReference(this);
        }
        return ret;
      }
    }

Note the `addReference` call.

### 17.4.2 Memory management for objects passed to the C++ layer

The example is a direct equivalent to this Java equivalent. Managing memory can be tricky when using C++ and C# proxy classes. The previous example shows one such case and this example looks at memory management for a class passed to a C++ method which expects the object to remain in scope after the function has returned. Consider the following two C++ classes:

    struct Element {
      int value;
      Element(int val) : value(val) {}
    };
    class Container {
      Element* element;
    public:
      Container() : element(0) {}
      void setElement(Element* e) { element = e; }
      Element* getElement() { return element; }
    };

and usage from C++

        Container container;
        Element element(20);
        container.setElement(&element);
        cout << "element.value: " << container.getElement()->value << endl;

and more or less equivalent usage from C#

          Container container = new Container();
          Element element = new Element(20);
          container.setElement(element);

The C++ code will always print out 20, but the value printed out may not be this in the C# equivalent code. In order to understand why, consider a garbage collection occuring...

          Container container = new Container();
          Element element = new Element(20);
          container.setElement(element);
          Console.WriteLine("element.value: " + container.getElement().value);
          // Simulate a garbage collection
          System.GC.Collect();
          System.GC.WaitForPendingFinalizers();
          Console.WriteLine("element.value: " + container.getElement().value);

The temporary element created with `new Element(20)` could get garbage collected which ultimately means the `container` variable is holding a dangling pointer, thereby printing out any old random value instead of the expected value of 20. One solution is to add in the appropriate references in the C# layer...

    public class Container : IDisposable {

      ...

      // Ensure that the GC doesn't collect any Element set from C#
      // as the underlying C++ class stores a shallow copy
      private Element elementReference;
      private HandleRef getCPtrAndAddReference(Element element) {
        elementReference = element;
        return Element.getCPtr(element);
      }

      public void setElement(Element e) {
        examplePINVOKE.Container_setElement(swigCPtr, getCPtrAndAddReference(e));
      }
    }

The following typemaps will generate the desired code. The 'csin' typemap matches the input parameter type for the `setElement` method. The 'cscode' typemap simply adds in the specified code into the C# proxy class.

    %typemap(csin) Element *e "getCPtrAndAddReference($csinput)"

    %typemap(cscode) Container %{
      // Ensure that the GC doesn't collect any Element set from C#
      // as the underlying C++ class stores a shallow copy
      private Element elementReference;
      private HandleRef getCPtrAndAddReference(Element element) {
        elementReference = element;
        return Element.getCPtr(element);
      }
    %}