Thunk

from Wikipedia, the free encyclopedia

In software development jargon, a thunk is the call to code that belongs to a different platform or framework . When changing from 16 to 32 bits, for example, the operating systems ( OS / 2 , Windows NT etc.) were able to implement 16-bit code by converting the call parameters and addresses accordingly, so that 16-bit programs could continue to be used. In modern software development, a thunk is e.g. B. calling native code from managed code and vice versa (see Java Native Access or .NET P / Invoke). It is a platform transition, in which the calling conventions and / or transfer parameters must be implemented accordingly ( marshaling ). The programming language C ++ / CLI from the .NET framework from Microsoft was specially designed to enable such thunks in both directions:

Managed-unmanaged call

Given a native C ++ class, e.g. B. in a C ++ project or as part of a C ++ / CLI project, which is subsequently used by managed code :

public class CNativeClass
{
  private:
    int m_i;
  public:
    void SetValue( int i )
    {
      m_i = i;
    }
};

Managed C ++ / CLI class (which can be instantiated directly in this form by, for example, C #), which uses the native class shown above:

public ref class CManagedClass
{
  public:
    CManagedClass()
    {
      System::Int32 i = 42;
      CNativeClass* pNativeClass = new CNativeClass();
      pNativeClass->SetValue( i );//Umsetzung des Datentyps
      delete pNativeClass;
    }
};

Unmanaged-managed call

Managed C ++ / CLI class:

public ref class CManagedClass
{
  private:
    System::Int32 m_i;
  public:
    void SetValue( int i )
    {
      m_i = i;//Umsetzung des Datentyps
    }
};

Native C ++ class in a C ++ / CLI project. Here you can see that the opposite way is also possible, namely the instantiation of managed code within an unmanaged class. However, it is a condition that it is a C ++ / CLI project so that the compiler understands the corresponding syntax. The thunk already occurs with the gcnew instruction, since the constructor of the managed class is called here:

public class CNativeClass
{
  public:
    void Foo()
    {
      int i = 42;
      CManagedClass^ pManagedClass = gcnew CManagedClass();
      pManagedClass->SetValue( i );
    }
};

literature

  • Marcus Heege: Expert C ++ / CLI . Apress Verlag, Berkeley 2007, ISBN 978-1-59059-756-9 , Chapter 9, from page 203.