20 SWIG and C#

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

20.1.1 SWIG 2 Compatibility

In order to minimize name collisions between names generated based on input to SWIG and names used in the generated code from the .NET framework, SWIG 3 fully qualifies the use of all .NET types. Furthermore, SWIG 3 avoids using directives in generated code. This breaks backwards compatibility with typemaps, pragmas, etc written for use with SWIG 2 that assume the presence of using System; or using System.Runtime.InteropServices; directives in the intermediate class imports, module imports, or proxy imports. SWIG 3 supports backwards compatibility though the use of the SWIG2_CSHARP macro. If SWIG2_CSHARP is defined, SWIG 3 generates using directives in the intermediate class, module class, and proxy class code similar to those generated by SWIG 2. This can be done without modifying any of the input code by passing the -DSWIG2_CSHARP commandline parameter when executing swig.

20.1.2 Additional command line options

The following table lists the additional commandline options available for the C# module. They can also be seen by using:

swig -csharp -help 
C# specific options
-dllimport <dl> Override DllImport attribute name to <dl>
-namespace <nm> Generate wrappers into C# namespace <nm>
-noproxy Generate the low-level functional interface instead of proxy classes
-oldvarnames Old intermediary method names for variable wrappers
-outfile <file> Write all C# into a single <file> located in the output directory

The -outfile option combines all the generated C# code into a single output file instead of creating multiple C# files. The default, when this option is not provided, is to generate separate .cs files for the module class, intermediary class and each of the generated proxy and type wrapper classes. Note that the file extension (.cs) will not be automatically added and needs to be provided. Due to possible compiler limits it is not advisable to use -outfile for large projects.

20.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:

$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. This also works with newer versions of Visual Studio if you allow it to convert the solution to the latest version. 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. After SWIG has run and both the C# and C/C++ compilers have finished building, the examples will be run, by either running runme.exe or by running mono runme.exe (Mono C# compiler). 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 C# compilers (Mono or Microsoft) can be detected from within a Cygwin or Mingw environment if installed in your path.

20.3 Void pointers

By default SWIG treats void * as any other pointer and hence marshalls it as a type wrapper class called SWIGTYPE_p_void. If you want to marshall with the .NET System.IntPtr type instead, there is a simple set of named typemaps called void *VOID_INT_PTR that can be used. They can be applied like any other named typemaps:

%apply void *VOID_INT_PTR { void * }
void * f(void *v);

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

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

20.4.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 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:

[global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_myArrayCopy")]
public static extern void myArrayCopy([global::System.Runtime.InteropServices.In, global::System.Runtime.InteropServices.MarshalAs(UnmanagedType.LPArray)]int[] jarg1, 
                                      [global::System.Runtime.InteropServices.Out, global::System.Runtime.InteropServices.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 intermediary class method

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

20.4.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((global::System.IntPtr)swig_ptrTo_sourceArray, (global::System.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 intermediary class method looks a little different from the default marshalling example - the method is expecting an IntPtr as the parameter type.

[global::System.Runtime.InteropServices.DllImport("example", EntryPoint="CSharp_myArrayCopy")]
public static extern void myArrayCopy(global::System.IntPtr jarg1, global::System.IntPtr jarg2, int jarg3);

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

20.5.1 C# exception example using "check" typemap

Let's 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.

20.5.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());
  return $null;
}
%}

%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();
  }

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

20.5.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);

    [global::System.Runtime.InteropServices.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 : global::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) {
  ...
}

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

20.6.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)

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

public class Base : global::System.IDisposable {
  private global::System.Runtime.InteropServices.HandleRef swigCPtr;
  protected bool swigCMemOwn;

  internal Base(global::System.IntPtr cPtr, bool cMemoryOwn) {
    swigCMemOwn = cMemoryOwn;
    swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
  }

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

  ~Base() {
    Dispose();
  }

  public virtual void Dispose() {
    lock(this) {
      if(swigCPtr.Handle != global::System.IntPtr.Zero && swigCMemOwn) {
        swigCMemOwn = false;
        examplePINVOKE.delete_Base(swigCPtr);
      }
      swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
      global::System.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, global::System.global::System.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(global::System.IntPtr b, bool flag) {
    BaseBoolMethod(new Base(b, false), flag);
  }

  public delegate uint SwigDelegateBase_0(uint x);
  public delegate void SwigDelegateBase_1(global::System.IntPtr b, bool flag);

  private SwigDelegateBase_0 swigDelegate0;
  private SwigDelegateBase_1 swigDelegate1;

  private static global::System.Type[] swigMethodTypes0 = new global::System.Type[] { typeof(uint) };
  private static global::System.Type[] swigMethodTypes1 = new global::System.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);
  }
}

The delegates from the above example are public by default:

  public delegate uint SwigDelegateBase_0(uint x);
  public delegate void SwigDelegateBase_1(global::System.IntPtr b, bool flag);

These can be changed if desired via the csdirectordelegatemodifiers %feature directive. For example, using %feature("csdirectordelegatemodifiers") "internal" before SWIG parses the Base class will change all the delegates to internal:

  internal delegate uint SwigDelegateBase_0(uint x);
  internal delegate void SwigDelegateBase_1(global::System.IntPtr b, bool flag);

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

20.7 Multiple modules

When using multiple modules it is is possible to compile each SWIG generated wrapper into a different assembly. However, by default the generated code may not compile if generated classes in one assembly use generated classes in another assembly. The visibility of the getCPtr() and pointer constructor generated from the csbody typemaps needs changing. The default visibility is internal but it needs to be public for access from a different assembly. Just changing 'internal' to 'public' in the typemap achieves this. Two macros are available in csharp.swg to make this easier and using them is the preferred approach over simply copying the typemaps and modifying as this is forward compatible with any changes in the csbody typemap in future versions of SWIG. The macros are for the proxy and typewrapper classes and can respectively be used to to make the method and constructor public:

  SWIG_CSBODY_PROXY(public, public, SWIGTYPE)
  SWIG_CSBODY_TYPEWRAPPER(public, public, public, SWIGTYPE)

Alternatively, instead of exposing these as public, consider using the [assembly:InternalsVisibleTo("Name")] attribute available in the .NET framework when you know which assemblies these can be exposed to. Another approach would be to make these public, but also to hide them from intellisense by using the [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] attribute if you don't want users to easily stumble upon these so called 'internal workings' of the wrappers.

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

20.8.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
      global::System.GC.Collect();
      global::System.GC.WaitForPendingFinalizers();
      global::System.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 {
    global::System.IntPtr cPtr = $imcall;$excode
    $csclassname ret = null;
    if (cPtr != global::System.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 : global::System.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 : global::System.IDisposable {
  ...
  public Wheel getWheel() {
    global::System.IntPtr cPtr = examplePINVOKE.Bike_getWheel(swigCPtr);
    Wheel ret = null;
    if (cPtr != global::System.IntPtr.Zero) {
      ret = new Wheel(cPtr, false);
      ret.addReference(this);
    }
    return ret;
  }
}

Note the addReference call.

20.8.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
      global::System.GC.Collect();
      global::System.GC.WaitForPendingFinalizers();
      global::System.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 : global::System.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 global::System.Runtime.InteropServices.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 global::System.Runtime.InteropServices.HandleRef getCPtrAndAddReference(Element element) {
    elementReference = element;
    return Element.getCPtr(element);
  }
%}

20.8.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 : global::System.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 : global::System.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 global::System.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:

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

20.8.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 Structure 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 {
      global::System.IntPtr cPtr = $imcall;
      CDate tempDate = (cPtr == global::System.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 {
      global::System.IntPtr cPtr = examplePINVOKE.ImportantDate_get();
      CDate tempDate = (cPtr == global::System.IntPtr.Zero) ? null : new CDate(cPtr, false);
      return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(),
                                 0, 0, 0);
    } 
  }
  ...
}

Some points to note:

20.8.5 Date example demonstrating the 'pre' and 'post' typemap attributes for directors

The 'pre' and 'post' attributes in the "csdirectorin" typemap act like the attributes of the same name in the "csin" typemap. For example if we modify the Date marshalling example like this:

class CDate {
  ...
  void setYear(int);
  void setMonth(int);
  void setDay(int);
};
struct Action {
  virtual void someCallback(CDate &date);
  virtual ~Action();
  ...
};

and declare %feature ("director") for the Action class, we would have to define additional marshalling rules for CDate & parameter. The typemap may look like this:

%typemap(csdirectorin,
         pre="System.DateTime temp$iminput = new System.DateTime();",
         post="CDate temp2$iminput = new CDate($iminput, false);\n"
              "temp2$iminput.setYear(tempdate.Year);\n"
              "temp2$iminput.setMonth(tempdate.Month);\n"
              "temp2$iminput.setDay(tempdate.Day);"
         ) CDate &date "out temp$iminput"

The generated proxy class code will then contain the following wrapper for calling user-overloaded someCallback():

...
  private void SwigDirectorsomeCallback(global::System.IntPtr date) {
    System.DateTime tempdate = new System.DateTime();
    try {
      someCallback(out tempdate);
    } finally {
      // we create a managed wrapper around the existing C reference, just for convenience
      CDate temp2date = new CDate(date, false);
      temp2date.setYear(tempdate.Year);
      temp2date.setMonth(tempdate.Month);
      temp2date.setDay(tempdate.Day);
    }
  }
...

Pay special attention to the memory management issues, using these attributes.

20.8.6 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 : global::System.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 : global::System.IDisposable {
  ...
  public int Part1() {
    ...
  }
}

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

public partial class ExtendMe : global::System.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.

20.8.7 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 : global::System.IDisposable {
  ...
  public int Part3() {
    return 3;
  }
  public int Part1() {
    ...
  }
}

20.8.8 Underlying type for enums

C# enums use int as the underlying type for each enum item. If you wish to change the underlying type to something else, then use the csbase typemap. For example when your C++ code uses a value larget than int, this is necessary as the C# compiler will not compile values which are too large to fit into an int. Here is an example:

%typemap(csbase) BigNumbers "uint"
%inline %{
  enum BigNumbers { big=0x80000000, bigger };
%}

The generated enum will then use the given underlying type and compile correctly:

public enum BigNumbers : uint {
  big = 0x80000000,
  bigger
}