Adapter functions

Top  Previous  Next

PInvoke > Adapter functions

Many API functions have parameters with pointer type. C# hasn't pointers at all, but it has the IntPtr type, which is used in such cases. In such cases Delphi2C# creates adapter-functions in addition to the original Delphi function declarations. Simulated pointers are passed to these adapter-functions and inside of the functions they are converted to IntPtr's, which then can be passed again to the real API function. If the pointer is used to retrieve a value from the unmanaged code, the IntPtr is converted back to the simulated pointer after the API call. This is a kind of "double-marshalling".


If, for example, the values for an Integer shall be retrieved from the unmanaged code, this can be done by a var parameter of a PInteger type:



procedure APIfoo(var pi : PInteger);





procedure APIfoo(var pi : PInteger); external bar32 name 'APIfoo';




Delphi2C# creates an adapter function with an "ref Pointer<int>" parameter. The simulated pointer types have a member function "ToIntPtr", which returns the needed IntPtr-value. However, this member function isn't called directly, but inside of a global function "ToIntPtr", which asserts that the simulated pointer isn't null.



[DllImport(bar32, SetLastError=true)]

public static extern void APIfoo(

                          /*ref*/ IntPtr pi);


public static void APIfoo(ref Pointer<int> pi)






"ToIntPrt" allocates some memory. This is freed in the subsequent call of  "FromIntPtr(lpFileTime)", which also writes the retrieved integer value back to the simulated pointer variable.



Adapter functions are created too, if a buffer of characters or a string has to be retrieved from the unmanaged code.







This page belongs to the Delphi2C# Documentation

Delphi2C# home  Content