Common datatypes

Top  Previous  Next

PInvoke > Common datatypes


The most simple case of calling Windows API functions from C# is, that all parameter and return types are isomorphic, i.e. they have a common representation in both managed and unmanaged memory. A simple example is the function GetCurrentThreadId. The Delphi code imports this funtion with the following lines of code:



function GetCurrentThreadId: DWORD; stdcall;

{$EXTERNALSYM GetCurrentThreadId}





function GetCurrentThreadId; external kernel32 name 'GetCurrentThreadId';



In C# this simply becomes to:


[DllImport(kernel32, SetLastError=true)]

public static extern uint /*stdcall*/ GetCurrentThread();



This function can be called in the code e.g. by:


uint CurThread = GetCurrentThreadId();




The conversion of the Delphi code also is straightforward in the following example of GetLocalTime, where a TSysteTime var parameter is passed.




  _SYSTEMTIME = record

    wYear: Word;

    wMonth: Word;

    wDayOfWeek: Word;

    wDay: Word;

    wHour: Word;

    wMinute: Word;

    wSecond: Word;

    wMilliseconds: Word;



  TSystemTime = _SYSTEMTIME;





procedure GetLocalTime(var lpSystemTime: TSystemTime); stdcall;





procedure GetLocalTime; external kernel32 name 'GetLocalTime';



The _SYSTEMTIME structure, that Delphi2C# generates for C# only consists in fields with data types, which need no special marshalling.


public struct _SYSTEMTIME


  public ushort wYear;

  public ushort wMonth;

  public ushort wDayOfWeek;

  public ushort wDay;

  public ushort wHour;

  public ushort wMinute;

  public ushort wSecond;

  public ushort wMilliseconds;

  public static _SYSTEMTIME CreateRecord(){return new _SYSTEMTIME();}



Therefore the GetLocalTime function also is converted quite easily:


[DllImport(kernel32, SetLastError=true)]

public static extern void /*stdcall*/ GetLocalTime(

                          ref _SYSTEMTIME lpSystemTime);



GetLocalTime is called inside of the SysUtils.Date-function:



  SystemTime: TSystemTime;





Delphi2C# automatically generates the following call:




GetLocalTime(ref SYSTEMTIME);







This page belongs to the Delphi2C# Documentation

Delphi2C# home  Content