# 18 SWIG and C#

- Introduction
- Differences to the Java module
- C# Arrays
  - The SWIG C arrays library
  - Managed arrays using P/Invoke default array marshalling
  - Managed arrays using pinning
- C# Exceptions
  - C# exception example using "check" typemap
  - C# exception example using %exception
  - C# exception example using exception specifications
  - Custom C# ApplicationException example
- C# Directors
  - Directors example
  - Directors implementation
  - Director caveats
- C# Typemap examples
  - Memory management when returning references to member variables
  - Memory management for objects passed to the C++ layer
  - Date marshalling using the csin typemap and associated attributes
  - A date example demonstrating marshalling of C# properties
  - Turning wrapped classes into partial classes
  - Extending proxy classes with additional C# code

## 18.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.

## 18.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 C# module has the same major SWIG features as the Java module. The rest of this section should be read in conjunction with the Java documentation as it lists the main differences. The most notable differences to Java are the following:

- When invoking SWIG use the `-csharp` command line option instead of `-java`.
- The `-nopgcpp` command line option does not exist.
- The `-package` command line option does not exist.
- The `-namespace <name>` commandline option will generate all code into the namespace specified by `<name>`. C# supports nested namespaces that are not lexically nested, so nested namespaces will of course also work. For example: `-namespace com.bloggs.widget`, will generate code into C# namespaces:

      namespace com.bloggs.widget {
        ...
      }

  Note that by default, the generated C# classes have no namespace and the module name is unrelated to namespaces. The module name is just like in Java and is merely used to name some of the generated classes.
- 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
      javadirectorin              -> csdirectorin
      javadirectorout             -> csdirectorout
      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
      $&javaclassname             -> $&csclassname
      $*javaclassname             -> $*csclassname
      $javainput                  -> $csinput
      $jnicall                    -> $imcall

- Unlike the "javain" typemap, the "csin" typemap does not support the 'pgcpp' attribute as the C# module does not have a premature garbage collection prevention parameter. The "csin" typemap supports additional optional attributes called 'cshin' and 'terminator'. The 'cshin' attribute should contain the parameter type and name whenever a constructor helper function is generated due to the 'pre' or 'post' attributes. The 'terminator' attribute normally just contains a closing brace for when the 'pre' attribute contains an opening brace, such as when a C# `using` or `fixed` block is started. Note that 'pre', 'post', 'terminator' and 'cshin' attributes are not used for marshalling the property set. Please see the Date marshalling example and Date marshalling of properties example for further understanding of these "csin" applicable attributes.

- 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 subtly 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. Note that the type used for the property is specified in the 'cstype' typemap. If the 'out' attribute exists in this typemap, then the type used is from the 'out' attribute.

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

- 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`.

- There is no additional 'premature garbage collection prevention parameter' as the marshalling of the `HandleRef` object takes care of ensuring a reference to the proxy class is held until the unmanaged call completed.

`$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.

## 18.3 C# Arrays

There are various ways to pass arrays from C# to C/C++. The default wrapping treats arrays as pointers and as such simple type wrapper classes are generated, eg `SWIGTYPE_p_int` when wrapping the C type `int []` or `int *`. This gives a rather restricted use of the underlying unmanaged code and the most practical way to use arrays is to enhance or customise with one of the following three approaches; namely the SWIG C arrays library, P/Invoke default array marshalling or pinned arrays.

### 18.3.1 The SWIG C arrays library

The C arrays library keeps all the array memory in the unmanaged layer. The library is available to all language modules and is documented in the carrays.i library section. Please refer to this section for details, but for convenience, the C# usage for the two examples outlined there is shown below.

For the `%array_functions` example, the equivalent usage would be:

    SWIGTYPE_p_double a = example.new_doubleArray(10);  // Create an array
    for (int i=0; i<10; i++)
      example.doubleArray_setitem(a,i,2*i);             // Set a value
    example.print_array(a);                             // Pass to C
    example.delete_doubleArray(a);                      // Destroy array

and for the `%array_class` example, the equivalent usage would be:

    doubleArray c = new doubleArray(10);    // Create double[10]
    for (int i=0; i<10; i++)
      c.setitem(i, 2*i);                    // Assign values
    example.print_array(c.cast());          // Pass to C

### 18.3.2 Managed arrays using P/Invoke default array marshalling

In the P/Invoke default marshalling scheme, one needs to designate whether the invoked function will treat a managed array parameter as input, output, or both. When the function is invoked, the CLR allocates a separate chunk of memory as big as the given managed array, which is automatically released at the end of the function call. If the array parameter is marked as being input, the content of the managed array is copied into this buffer when the call is made. Correspondingly, if the array parameter is marked as being output, the contents of the reserved buffer are copied back into the managed array after the call returns. A pointer to to this buffer is passed to the native function.

The reason for allocating a separate buffer is to leave the CLR free to relocate the managed array object during garbage collection. If the overhead caused by the copying is causing a significant performance penalty, consider pinning the managed array and passing a direct reference as described in the next section.

For more information on the subject, see the Default Marshaling for Arrays article on MSDN.

The P/Invoke default marshalling is supported by the `arrays_csharp.i` library via the INPUT, OUTPUT and INOUT typemaps. Let's look at some example usage. Consider the following C function:

    void myArrayCopy(int *sourceArray, int *targetArray, int nitems);

We can now instruct SWIG to use the default marshalling typemaps by

    %include "arrays_csharp.i"

    %apply int INPUT[]  {int *sourceArray}
    %apply int OUTPUT[] {int *targetArray}

As a result, we get the following method in the module class:

    public static void myArrayCopy(int[] sourceArray, int[] targetArray, int nitems) {
        examplePINVOKE.myArrayCopy(sourceArray, targetArray, nitems);
    }

If we look beneath the surface at the corresponding intermediary class code, we see that SWIG has generated code that uses attributes (from the System.Runtime.InteropServices namespace) to tell the CLR to use default marshalling for the arrays:

    [DllImport("example", EntryPoint="CSharp_myArrayCopy")]
    public static extern void myArrayCopy([In, MarshalAs(UnmanagedType.LPArray)]int[] jarg1,
                                          [Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2, int jarg3);

As an example of passing an inout array (i.e. the target function will both read from and write to the array), consider this C function that swaps a given number of elements in the given arrays:

    void myArraySwap(int *array1, int *array2, int nitems);

Now, we can instruct SWIG to wrap this by

    %include "arrays_csharp.i"

    %apply int INOUT[] {int *array1}
    %apply int INOUT[] {int *array2}

This results in the module class method

      public static void myArraySwap(int[] array1, int[] array2, int nitems) {
        examplePINVOKE.myArraySwap(array1, array2, nitems);
      }

and intermediate class method

      [DllImport("example", EntryPoint="CSharp_myArraySwap")]
      public static extern void myArraySwap([In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg1,
                                            [In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2, int jarg3);

### 18.3.3 Managed arrays using pinning

It is also possible to pin a given array in memory (i.e. fix its location in memory), obtain a direct pointer to it, and then pass this pointer to the wrapped C/C++ function. This approach involves no copying, but it makes the work of the garbage collector harder as the managed array object can not be relocated before the fix on the array is released. You should avoid fixing arrays in memory in cases where the control may re-enter the managed side via a callback and/or another thread may produce enough garbage to trigger garbage collection.

For more information, see the fixed statement in the C# language reference.

Now let's look at an example using pinning, thus avoiding the CLR making copies of the arrays passed as parameters. The `arrays_csharp.i` library file again provides the required support via the `FIXED` typemaps. Let's use the same function from the previous section:

    void myArrayCopy(int *sourceArray, int *targetArray, int nitems);

We now need to declare the module class method unsafe, as we are using pointers:

    %csmethodmodifiers myArrayCopy "public unsafe";

Apply the appropriate typemaps to the array parameters:

    %include "arrays_csharp.i"

    %apply int FIXED[] {int *sourceArray}
    %apply int FIXED[] {int *targetArray}

Notice that there is no need for separate in, out or inout typemaps as is the case when using P/Invoke default marshalling.

As a result, we get the following method in the module class:

      public unsafe static void myArrayCopy(int[] sourceArray, int[] targetArray, int nitems) {
        fixed ( int *swig_ptrTo_sourceArray = sourceArray ) {
        fixed ( int *swig_ptrTo_targetArray = targetArray ) {
        {
          examplePINVOKE.myArrayCopy((IntPtr)swig_ptrTo_sourceArray, (IntPtr)swig_ptrTo_targetArray, nitems);
        }
        }
        }
      }

On the method signature level the only difference to the version using P/Invoke default marshalling is the "unsafe" quantifier, which is required because we are handling pointers.

Also the intermediate class method looks a little different from the default marshalling example - the method is expecting an IntPtr as the parameter type.

    [DllImport("example", EntryPoint="CSharp_myArrayCopy")]
    public static extern void myArrayCopy(IntPtr jarg1, IntPtr jarg2, int jarg3);

## 18.4 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 notably 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_CSharpInvalidCastException,
      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.

### 18.4.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`.

### 18.4.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();
      }

### 18.4.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.

### 18.4.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) {
      ...
    }

## 18.5 C# Directors

The SWIG directors feature adds extra code to the generated C# proxy classes that enable these classes to be used in cross-language polymorphism. Essentially, it enables unmanaged C++ code to call back into managed code for virtual methods so that a C# class can derive from a wrapped C++ class.

The following sections provide information on the C# director implementation and contain most of the information required to use the C# directors. However, the Java directors section should also be read in order to gain more insight into directors.

### 18.5.1 Directors example

Imagine we are wrapping a C++ base class, `Base`, from which we would like to inherit in C#. Such a class is shown below as well as another class, `Caller`, which calls the virtual method `UIntMethod` from pure unmanaged C++ code.

    // file: example.h
    class Base {
    public:
      virtual ~Base() {}

      virtual unsigned int UIntMethod(unsigned int x) {
        std::cout << "Base - UIntMethod(" << x << ")" << std::endl;
        return x;
      }
      virtual void BaseBoolMethod(const Base &b, bool flag) {}
    };

    class Caller {
    public:
      Caller(): m_base(0) {}
      ~Caller() { delBase(); }
      void set(Base *b) { delBase(); m_base = b; }
      void reset() { m_base = 0; }
      unsigned int UIntMethodCall(unsigned int x) { return m_base->UIntMethod(x); }

    private:
      Base *m_base;
      void delBase() { delete m_base; m_base = 0; }
    };

The director feature is turned off by default and the following simple interface file shows how directors are enabled for the class `Base`.

    /* File : example.i */
    %module(directors="1") example
    %{
    #include "example.h"
    %}

    %feature("director") Base;

    %include "example.h"

The following is a C# class inheriting from `Base`:

    public class CSharpDerived : Base
    {
      public override uint UIntMethod(uint x)
      {
        Console.WriteLine("CSharpDerived - UIntMethod({0})", x);
        return x;
      }
    }

The `Caller` class can demonstrate the `UIntMethod` method being called from unmanaged code using the following C# code:

    public class runme
    {
      static void Main()
      {
        Caller myCaller = new Caller();

        // Test pure C++ class
        using (Base myBase = new Base())
        {
          makeCalls(myCaller, myBase);
        }

        // Test director / C# derived class
        using (Base myBase = new CSharpDerived())
        {
          makeCalls(myCaller, myBase);
        }
      }

      static void makeCalls(Caller myCaller, Base myBase)
      {
        myCaller.set(myBase);
        myCaller.UIntMethodCall(123);
        myCaller.reset();
      }
    }

If the above is run, the output is then:

    Base - UIntMethod(123)
    CSharpDerived - UIntMethod(123)

### 18.5.2 Directors implementation

The previous section demonstrated a simple example where the virtual `UIntMethod` method was called from C++ code, even when the overridden method is implemented in C#. The intention of this section is to gain an insight into how the director feature works. It shows the generated code for the two virtual methods, `UIntMethod` and `BaseBoolMethod`, when the director feature is enabled for the `Base` class.

Below is the generated C# `Base` director class.

    using System;
    using System.Runtime.InteropServices;

    public class Base : IDisposable {
      private HandleRef swigCPtr;
      protected bool swigCMemOwn;

      internal Base(IntPtr cPtr, bool cMemoryOwn) {
        swigCMemOwn = cMemoryOwn;
        swigCPtr = new HandleRef(this, cPtr);
      }

      internal static HandleRef getCPtr(Base obj) {
        return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
      }

      ~Base() {
        Dispose();
      }

      public virtual void Dispose() {
        lock(this) {
          if(swigCPtr.Handle != IntPtr.Zero && swigCMemOwn) {
            swigCMemOwn = false;
            examplePINVOKE.delete_Base(swigCPtr);
          }
          swigCPtr = new HandleRef(null, IntPtr.Zero);
          GC.SuppressFinalize(this);
        }
      }

      public virtual uint UIntMethod(uint x) {
        uint ret = examplePINVOKE.Base_UIntMethod(swigCPtr, x);
        return ret;
      }

      public virtual void BaseBoolMethod(Base b, bool flag) {
        examplePINVOKE.Base_BaseBoolMethod(swigCPtr, Base.getCPtr(b), flag);
        if (examplePINVOKE.SWIGPendingException.Pending)
          throw examplePINVOKE.SWIGPendingException.Retrieve();
      }

      public Base() : this(examplePINVOKE.new_Base(), true) {
        SwigDirectorConnect();
      }

      private void SwigDirectorConnect() {
        if (SwigDerivedClassHasMethod("UIntMethod", swigMethodTypes0))
          swigDelegate0 = new SwigDelegateBase_0(SwigDirectorUIntMethod);
        if (SwigDerivedClassHasMethod("BaseBoolMethod", swigMethodTypes1))
          swigDelegate1 = new SwigDelegateBase_1(SwigDirectorBaseBoolMethod);
        examplePINVOKE.Base_director_connect(swigCPtr, swigDelegate0, swigDelegate1);
      }

      private bool SwigDerivedClassHasMethod(string methodName, Type[] methodTypes) {
        System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(methodName, methodTypes);
        bool hasDerivedMethod = methodInfo.DeclaringType.IsSubclassOf(typeof(Base));
        return hasDerivedMethod;
      }

      private uint SwigDirectorUIntMethod(uint x) {
        return UIntMethod(x);
      }

      private void SwigDirectorBaseBoolMethod(IntPtr b, bool flag) {
        BaseBoolMethod(new Base(b, false), flag);
      }

      internal delegate uint SwigDelegateBase_0(uint x);
      internal delegate void SwigDelegateBase_1(IntPtr b, bool flag);

      private SwigDelegateBase_0 swigDelegate0;
      private SwigDelegateBase_1 swigDelegate1;

      private static Type[] swigMethodTypes0 = new Type[] { typeof(uint) };
      private static Type[] swigMethodTypes1 = new Type[] { typeof(Base), typeof(bool) };
    }

Everything from the `SwigDirectorConnect()` method and below is code that is only generated when directors are enabled. The design comprises a C# delegate being initialised for each virtual method on construction of the class. Let's examine the `BaseBoolMethod`.

In the `Base` constructor a call is made to `SwigDirectorConnect()` which contains the initialisation code for all the virtual methods. It uses a support method, `SwigDerivedClassHasMethod()`, which simply uses reflection to determine if the named method, BaseBoolMethod, with the list of required parameter types, exists in a subclass. If it does not exist, the delegate is not initialised as there is no need for unmanaged code to call back into managed C# code. However, if there is an overridden method in any subclass, the delegate is required. It is then initialised to the `SwigDirectorBaseBoolMethod` which in turn will call `BaseBoolMethod` if invoked. The delegate is not initialised to the `BaseBoolMethod` directly as quite often types will need marshalling from the unmanaged type to the managed type in which case an intermediary method (`SwigDirectorBaseBoolMethod`) is required for the marshalling. In this case, the C# `Base` class needs to be created from the unmanaged `IntPtr` type.

The last thing that `SwigDirectorConnect()` does is to pass the delegates to the unmanaged code. It calls the intermediary method `Base_director_connect()` which is really a call to the C function `CSharp_Base_director_connect()`. This method simply maps each C# delegate onto a C function pointer.

    SWIGEXPORT void SWIGSTDCALL CSharp_Base_director_connect(void *objarg,
                                            SwigDirector_Base::SWIG_Callback0_t callback0,
                                            SwigDirector_Base::SWIG_Callback1_t callback1) {
      Base *obj = (Base *)objarg;
      SwigDirector_Base *director = dynamic_cast<SwigDirector_Base *>(obj);
      if (director) {
        director->swig_connect_director(callback0, callback1);
      }
    }

    class SwigDirector_Base : public Base, public Swig::Director {
    public:
        SwigDirector_Base();
        virtual unsigned int UIntMethod(unsigned int x);
        virtual ~SwigDirector_Base();
        virtual void BaseBoolMethod(Base const &b, bool flag);

        typedef unsigned int (SWIGSTDCALL* SWIG_Callback0_t)(unsigned int);
        typedef void (SWIGSTDCALL* SWIG_Callback1_t)(void *, unsigned int);
        void swig_connect_director(SWIG_Callback0_t callbackUIntMethod,
                                   SWIG_Callback1_t callbackBaseBoolMethod);

    private:
        SWIG_Callback0_t swig_callbackUIntMethod;
        SWIG_Callback1_t swig_callbackBaseBoolMethod;
        void swig_init_callbacks();
    };

    void SwigDirector_Base::swig_connect_director(SWIG_Callback0_t callbackUIntMethod,
                                                  SWIG_Callback1_t callbackBaseBoolMethod) {
      swig_callbackUIntMethod = callbackUIntMethod;
      swig_callbackBaseBoolMethod = callbackBaseBoolMethod;
    }

Note that for each director class SWIG creates an unmanaged director class for making the callbacks. For example `Base` has `SwigDirector_Base` and `SwigDirector_Base` is derived from `Base`. Should a C# class be derived from `Base`, the underlying C++ `SwigDirector_Base` is created rather than `Base`. The `SwigDirector_Base` class then implements all the virtual methods, redirecting calls up to managed code if the callback/delegate is non-zero. The implementation of `SwigDirector_Base::BaseBoolMethod` shows this - the callback is made by invoking the `swig_callbackBaseBoolMethod` function pointer:

    void SwigDirector_Base::BaseBoolMethod(Base const &b, bool flag) {
      void * jb = 0 ;
      unsigned int jflag  ;

      if (!swig_callbackBaseBoolMethod) {
        Base::BaseBoolMethod(b,flag);
        return;
      } else {
        jb = (Base *) &b;
        jflag = flag;
        swig_callbackBaseBoolMethod(jb, jflag);
      }
    }

### 18.5.3 Director caveats

There is a subtle gotcha with directors. If default parameters are used, it is recommended to follow a pattern of always calling a single method in any C# derived class. An example will clarify this and the reasoning behind the recommendation. Consider the following C++ class wrapped as a director class:

    class Defaults {
    public:
      virtual ~Defaults();
      virtual void DefaultMethod(int a=-100);
    };

Recall that C++ methods with default parameters generate overloaded methods for each defaulted parameter, so a C# derived class can be created with two `DefaultMethod` override methods:

    public class CSharpDefaults : Defaults
    {
      public override void DefaultMethod()
      {
        DefaultMethod(-100); // note C++ default value used
      }
      public override void DefaultMethod(int x)
      {
      }
    }

It may not be clear at first, but should a user intend to call `CSharpDefaults.DefaultMethod()` from C++, a call is actually made to `CSharpDefaults.DefaultMethod(int)`. This is because the initial call is made in C++ and therefore the `DefaultMethod(int)` method will be called as is expected with C++ calls to methods with defaults, with the default being set to -100. The callback/delegate matching this method is of course the overloaded method `DefaultMethod(int)`. However, a call from C# to `CSharpDefaults.DefaultMethod()` will of course call this exact method and in order for behaviour to be consistent with calls from C++, the implementation should pass the call on to `CSharpDefaults.DefaultMethod(int)`using the C++ default value, as shown above.

## 18.6 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.

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

This example shows how to prevent premature 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 premature 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.

### 18.6.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);
      }
    %}

### 18.6.3 Date marshalling using the csin typemap and associated attributes

The NaN Exception example is a simple example of the "javain" typemap and its 'pre' attribute. This example demonstrates how a C++ date class, say `CDate`, can be mapped onto the standard .NET date class, `System.DateTime` by using the 'pre', 'post' and 'pgcppname' attributes of the "csin" typemap (the C# equivalent to the "javain" typemap). The example is an equivalent to the Java Date marshalling example. The idea is that the `System.DateTime` is used wherever the C++ API uses a `CDate`. Let's assume the code being wrapped is as follows:

    class CDate {
    public:
      CDate();
      CDate(int year, int month, int day);
      int getYear();
      int getMonth();
      int getDay();
      ...
    };
    struct Action {
      static int doSomething(const CDate &dateIn, CDate &dateOut);
      Action(const CDate &date, CDate &dateOut);
    };

Note that `dateIn` is const and therefore read only and `dateOut` is a non-const output type.

First let's look at the code that is generated by default, where the C# proxy class `CDate` is used in the proxy interface:

    public class Action : IDisposable {
      ...
      public Action(CDate dateIn, CDate dateOut)
          : this(examplePINVOKE.new_Action(CDate.getCPtr(dateIn), CDate.getCPtr(dateOut)), true) {
        if (examplePINVOKE.SWIGPendingException.Pending)
          throw examplePINVOKE.SWIGPendingException.Retrieve();
      }

      public int doSomething(CDate dateIn, CDate dateOut) {
        int ret = examplePINVOKE.Action_doSomething(swigCPtr,
                                                    CDate.getCPtr(dateIn),
                                                    CDate.getCPtr(dateOut));
        if (examplePINVOKE.SWIGPendingException.Pending)
          throw examplePINVOKE.SWIGPendingException.Retrieve();
        return ret;
      }
    }

The `CDate &` and `const CDate &` C# code is generated from the following two default typemaps:

    %typemap(cstype) SWIGTYPE & "$csclassname"
    %typemap(csin) SWIGTYPE & "$csclassname.getCPtr($csinput)"

where '$csclassname' is translated into the proxy class name, `CDate` and '$csinput' is translated into the name of the parameter, eg `dateIn`. From C#, the intention is then to call into a modifed API with something like:

    System.DateTime dateIn = new System.DateTime(2011, 4, 13);
    System.DateTime dateOut = new System.DateTime();

    // Note in calls below, dateIn remains unchanged and dateOut
    // is set to a new value by the C++ call
    Action action = new Action(dateIn, out dateOut);
    dateIn = new System.DateTime(2012, 7, 14);

To achieve this mapping, we need to alter the default code generation slightly so that at the C# layer, a `System.DateTime` is converted into a `CDate`. The intermediary layer will still take a pointer to the underlying `CDate` class. The typemaps to achieve this are shown below.

    %typemap(cstype) const CDate& "System.DateTime"
    %typemap(csin,
             pre="    CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);"
            ) const CDate &
             "$csclassname.getCPtr(temp$csinput)"

    %typemap(cstype) CDate& "out System.DateTime"
    %typemap(csin,
             pre="    CDate temp$csinput = new CDate();",
             post="      $csinput = new System.DateTime(temp$csinput.getYear(),"
                  " temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);",
             cshin="out $csinput"
            ) CDate &
             "$csclassname.getCPtr(temp$csinput)"

The resulting generated proxy code in the `Action` class follows:

    public class Action : IDisposable {
      ...
      public int doSomething(System.DateTime dateIn, out System.DateTime dateOut) {
        CDate tempdateIn = new CDate(dateIn.Year, dateIn.Month, dateIn.Day);
        CDate tempdateOut = new CDate();
        try {
          int ret = examplePINVOKE.Action_doSomething(swigCPtr,
                                                      CDate.getCPtr(tempdateIn),
                                                      CDate.getCPtr(tempdateOut));
          if (examplePINVOKE.SWIGPendingException.Pending)
            throw examplePINVOKE.SWIGPendingException.Retrieve();
          return ret;
        } finally {
          dateOut = new System.DateTime(tempdateOut.getYear(),
                                        tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
        }
      }

      static private IntPtr SwigConstructAction(System.DateTime dateIn, out System.DateTime dateOut) {
        CDate tempdateIn = new CDate(dateIn.Year, dateIn.Month, dateIn.Day);
        CDate tempdateOut = new CDate();
        try {
          return examplePINVOKE.new_Action(CDate.getCPtr(tempdateIn), CDate.getCPtr(tempdateOut));
        } finally {
          dateOut = new System.DateTime(tempdateOut.getYear(),
                                        tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
        }
      }

      public Action(System.DateTime dateIn, out System.DateTime dateOut)
          : this(Action.SwigConstructAction(dateIn, out dateOut), true) {
        if (examplePINVOKE.SWIGPendingException.Pending)
          throw examplePINVOKE.SWIGPendingException.Retrieve();
      }
    }

A few things to note:

- The "cstype" typemap has changed the parameter type to `System.DateTime` instead of the default generated `CDate` proxy.
- The non-const `CDate &` type is marshalled as a reference parameter in C# as the date cannot be explicitly set once the object has been created, so a new object is created instead.
- The code in the 'pre' attribute appears before the intermediary call (`examplePINVOKE.new_Action` / `examplePINVOKE.Action_doSomething`).
- The code in the 'post' attribute appears after the intermediary call.
- A try .. finally block is generated with the intermediary call in the try block and 'post' code in the finally block. The alternative of just using a temporary variable for the return value from the intermediary call and the 'post' code being inserted before the return statement is not possible given that the intermediary call and method return comes from a single source (the "csout" typemap).
- The temporary variables in the "csin" typemaps are called `temp$csin`, where "$csin" is replaced with the parameter name. "$csin" is used to mangle the variable name so that more than one `CDate &` type can be used as a parameter in a method, otherwise two or more local variables with the same name would be generated.
- The use of the "csin" typemap causes a constructor helper function (`SwigConstructAction`) to be generated. This allows C# code to be called before the intermediary call made in the constructor initialization list.
- The 'cshin' attribute is required for the `SwigConstructAction` constructor helper function so that the 2nd parameter is declared as `out dateOut` instead of just `dateOut`.

So far we have considered the date as an input only and an output only type. Now let's consider `CDate *` used as an input/output type. Consider the following C++ function which modifies the date passed in:

    void addYears(CDate *pDate, int years) {
      *pDate = CDate(pDate->getYear() + years, pDate->getMonth(), pDate->getDay());
    }

If usage of `CDate *` commonly follows this input/output pattern, usage from C# like the following

    System.DateTime christmasEve = new System.DateTime(2000, 12, 24);
    example.addYears(ref christmasEve, 10); // christmasEve now contains 2010-12-24

will be possible with the following `CDate *` typemaps

    %typemap(cstype, out="System.DateTime") CDate * "ref System.DateTime"

    %typemap(csin,
             pre="    CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);",
             post="      $csinput = new System.DateTime(temp$csinput.getYear(),"
                  " temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);",
             cshin="ref $csinput"
            ) CDate *
             "$csclassname.getCPtr(temp$csinput)"

Globals are wrapped by the module class and for a module called example, the typemaps result in the following code:

    public class example {
      public static void addYears(ref System.DateTime pDate, int years) {
        CDate temppDate = new CDate(pDate.Year, pDate.Month, pDate.Day);
        try {
          examplePINVOKE.addYears(CDate.getCPtr(temppDate), years);
        } finally {
          pDate = new System.DateTime(temppDate.getYear(), temppDate.getMonth(), temppDate.getDay(), 0, 0, 0);
        }
      }
      ...
    }

The following typemap is the same as the previous but demonstrates how a using block can be used for the temporary variable. The only change to the previous typemap is the introduction of the 'terminator' attribute to terminate the `using` block. The `subtractYears` method is nearly identical to the above `addYears` method.

    %typemap(csin,
             pre="    using (CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day)) {",
             post="      $csinput = new System.DateTime(temp$csinput.getYear(),"
                  " temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);",
             terminator="    } // terminate temp$csinput using block",
             cshin="ref $csinput"
            ) CDate *
             "$csclassname.getCPtr(temp$csinput)"

    void subtractYears(CDate *pDate, int years) {
      *pDate = CDate(pDate->getYear() - years, pDate->getMonth(), pDate->getDay());
    }

The resulting generated code shows the termination of the `using` block:

    public class example {
      public static void subtractYears(ref System.DateTime pDate, int years) {
        using (CDate temppDate = new CDate(pDate.Year, pDate.Month, pDate.Day)) {
        try {
          examplePINVOKE.subtractYears(CDate.getCPtr(temppDate), years);
        } finally {
          pDate = new System.DateTime(temppDate.getYear(), temppDate.getMonth(), temppDate.getDay(), 0, 0, 0);
        }
        } // terminate temppDate using block
      }
      ...
    }

### 18.6.4 A date example demonstrating marshalling of C# properties

The previous section looked at converting a C++ date class to `System.DateTime` for parameters. This section extends this idea so that the correct marshalling is obtained when wrapping C++ variables. Consider the same `CDate` class from the previous section and a global variable:

    CDate ImportantDate = CDate(1999, 12, 31);

The aim is to use `System.DateTime` from C# when accessing this date as shown in the following usage where the module name is 'example':

    example.ImportantDate = new System.DateTime(2000, 11, 22);
    System.DateTime importantDate = example.ImportantDate;
    Console.WriteLine("Important date: " + importantDate);

When SWIG wraps a variable that is a class/struct/union, it is wrapped using a pointer to the type for the reasons given in Stucture data members. The typemap type required is thus `CDate *`. Given that the previous section already designed `CDate *` typemaps, we'll use those same typemaps plus the 'csvarin' and 'csvarout' typemaps.

    %typemap(cstype, out="System.DateTime") CDate * "ref System.DateTime"

    %typemap(csin,
             pre="    CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);",
             post="      $csinput = new System.DateTime(temp$csinput.getYear(),"
                  " temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);",
             cshin="ref $csinput"
            ) CDate *
             "$csclassname.getCPtr(temp$csinput)"

    %typemap(csvarin, excode=SWIGEXCODE2) CDate * %{
        /* csvarin typemap code */
        set {
          CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);
          $imcall;$excode
        } %}

    %typemap(csvarout, excode=SWIGEXCODE2) CDate * %{
        /* csvarout typemap code */
        get {
          IntPtr cPtr = $imcall;
          CDate tempDate = (cPtr == IntPtr.Zero) ? null : new CDate(cPtr, $owner);$excode
          return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(),
                                     0, 0, 0);
        } %}

For a module called example, the typemaps result in the following code:

    public class example {
      public static System.DateTime ImportantDate {
        /* csvarin typemap code */
        set {
          CDate tempvalue = new CDate(value.Year, value.Month, value.Day);
          examplePINVOKE.ImportantDate_set(CDate.getCPtr(tempvalue));
        }
        /* csvarout typemap code */
        get {
          IntPtr cPtr = examplePINVOKE.ImportantDate_get();
          CDate tempDate = (cPtr == IntPtr.Zero) ? null : new CDate(cPtr, false);
          return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(),
                                     0, 0, 0);
        }
      }
      ...
    }

Some points to note:

- The property set comes from the 'csvarin' typemap and the property get comes from the 'csvarout' typemap.
- The type used for the property comes from the 'cstype' typemap. This particular example has the 'out' attribute set in the typemap and as it is specified, it is used in preference to the type in the typemap body. This is because the type in the 'out' attribute can never include modifiers such as 'ref', thereby avoiding code such as `public static ref System.DateTime ImportantDate { ...`, which would of course not compile.
- The `$excode` special variable expands to nothing as there are no exception handlers specified in any of the unmanaged code typemaps (in fact the marshalling was done using the default unmanaged code typemaps.)
- The `$imcall` typemap expands to the appropriate intermediary method call in the `examplePINVOKE` class.
- The `$csinput` special variable in the 'csin' typemap always expands to `value` for properties. In this case `$csclassname.getCPtr(temp$csinput)` expands to `CDate.getCPtr(tempvalue)`.
- The 'csin' typemap has 'pre', 'post' and 'cshin' attributes, and these are all ignored in the property set. The code in these attributes must instead be replicated within the 'csvarin' typemap. The line creating the `temp$csinput` variable is such an example; it is identical to what is in the 'pre' attribute.

### 18.6.5 Turning wrapped classes into partial classes

C# supports the notion of partial classes whereby a class definition can be split into more than one file. It is possible to turn the wrapped C++ class into a partial C# class using the `csclassmodifiers` typemap. Consider a C++ class called `ExtendMe`:

    class ExtendMe {
    public:
      int Part1() { return 1; }
    };

The default C# proxy class generated is:

    public class ExtendMe : IDisposable {
      ...
      public int Part1() {
        ...
      }
    }

The default csclassmodifiers typemap shipped with SWIG is

    %typemap(csclassmodifiers) SWIGTYPE "public class"

Note that the type used is the special catch all type `SWIGTYPE`. If instead we use the following typemap to override this for just the `ExtendMe` class:

    %typemap(csclassmodifiers) ExtendMe "public partial class"

The C# proxy class becomes a partial class:

    public partial class ExtendMe : IDisposable {
      ...
      public int Part1() {
        ...
      }
    }

You can then of course declare another part of the partial class elsewhere, for example:

    public partial class ExtendMe : IDisposable {
      public int Part2() {
        return 2;
      }
    }

and compile the following code:

    ExtendMe em = new ExtendMe();
    Console.WriteLine("part1: {0}", em.Part1());
    Console.WriteLine("part2: {0}", em.Part2());

demonstrating that the class contains methods calling both unmanaged code - `Part1()` and managed code - `Part2()`. The following example is an alternative approach to adding managed code to the generated proxy class.

### 18.6.6 Extending proxy classes with additional C# code

The previous example showed how to use partial classes to add functionality to a generated C# proxy class. It is also possible to extend a wrapped struct/class with C/C++ code by using the %extend directive. A third approach is to add some C# methods into the generated proxy class with the `cscode` typemap. If we declare the following typemap before SWIG parses the `ExtendMe` class used in the previous example

    %typemap(cscode) ExtendMe %{
      public int Part3() {
        return 3;
      }
    %}

The generated C# proxy class will instead be:

    public class ExtendMe : IDisposable {
      ...
      public int Part3() {
        return 3;
      }
      public int Part1() {
        ...
      }
    }