17 SWIG and C#

17.1 Introduction

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

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

17.2 Differences to the Java module

The C# module is very similar to the Java module, so until some more complete documentation has been written, please use the Java documentation as a guide to using SWIG with C#. The 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. If your SWIG installation went well on a Unix environment and your C# compiler was detected, you should be able to type make in each example directory, then ilrun runme.exe (Portable.NET C# compiler) or mono runme.exe (Mono C# compiler) to run the examples. Windows users can also get the examples working using a Cygwin or MinGW environment for automatic configuration of the example makefiles. Any one of the three C# compilers (Portable.NET, Mono or Microsoft) can be detected from within a Cygwin or Mingw environment if installed in your path.

17.3 C# Exceptions

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

Unfortunately a C# exception cannot simply be thrown from unmanaged code for a variety of reasons. Most 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_CSharpInvalidOperationException,
  SWIG_CSharpIOException,
  SWIG_CSharpNullReferenceException,
  SWIG_CSharpOutOfMemoryException,
  SWIG_CSharpOverflowException,
  SWIG_CSharpSystemException
} SWIG_CSharpExceptionCodes;

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

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

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

17.3.1 C# exception example using "check" typemap

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

void positivesonly(int number);

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

%module example

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

%inline %{

void positivesonly(int number) {
}

%}

When the following C# code is executed:

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

The exception is thrown:

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

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

SWIGEXPORT void SWIGSTDCALL CSharp_positivesonly(int jarg1) {
    int arg1 ;
    
    arg1 = (int)jarg1; 
    
    if (arg1 < 0) {
        SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
                                               "only positive numbers accepted", "number");
        return ;
    }
    
    positivesonly(arg1);
    
}

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

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

}

This comes largely from the "csout" typemap.

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

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

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

}

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

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

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

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

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

17.3.2 C# exception example using %exception

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

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

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

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

SWIGEXPORT void SWIGSTDCALL CSharp_negativesonly(int jarg1) {
    int arg1 ;
    
    arg1 = (int)jarg1; 
    
    try {
        negativesonly(arg1);
        
    } catch (std::out_of_range e) {
        SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
        return ;
    }
    
}

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

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

17.3.3 C# exception example using exception specifications

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

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

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

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

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

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

17.3.4 Custom C# ApplicationException example

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

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

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

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

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

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

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

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

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

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

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

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

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

and the SWIG interface code:

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

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

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

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

17.4 C# 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.

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

17.4.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);
  }
}

17.4.3 Director caveats

There are a few gotchas with directors. The first is that the base class virtual method should not be called directly otherwise a stack overflow will occur due to recursive calls. This might be fixed in a future version of SWIG, but is likely to slow down virtual methods calls. For example, given Base as a director enabled class:

class Base {
public:
  virtual ~Base();
  virtual unsigned int UIntMethod(unsigned int x);
};

Do not directly call the base method from a C# derived class:

public class CSharpDerived : Base
{
  public override uint UIntMethod(uint x)
  {
    return base.UIntMethod(x);
  }
}

Secondly, 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.

17.5 C# Typemap examples

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

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

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