Array size attribute

Top  Previous  Next

PInvoke > Array size attribute

 

In the next example a record is marshalled, which has array fields with a fixed array size.

 

type

  PCPInfo = ^TCPInfo;

  {$EXTERNALSYM _cpinfo}

  _cpinfo = record

    MaxCharSize: UINT;                       { max length (bytes) of a char }

    DefaultChar: array[0..MAX_DEFAULTCHAR - 1] of Byte; { default character }

    LeadByte: array[0..MAX_LEADBYTES - 1] of Byte;      { lead byte ranges }

  end;

  TCPInfo = _cpinfo;

  {$EXTERNALSYM CPINFO}

  CPINFO = _cpinfo;

 

{$EXTERNALSYM GetCPInfo}

function GetCPInfo(CodePage: UINT; var lpCPInfo: TCPInfo): BOOL; stdcall;

 

implementation

 

function GetCPInfo; external kernel32 name 'GetCPInfo';

 

 

In this case attributes have to be set to the according fields:

 

 

public struct _cpinfo

{

  public uint MaxCharSize;                       /* max length (bytes) of a char */

  [MarshalAs(UnmanagedType.ByValArray, SizeConst=2)] public byte[] DefaultChar; /* default character */

  [MarshalAs(UnmanagedType.ByValArray, SizeConst=12)] public byte[] LeadByte;      /* lead byte ranges */

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

};

 

 

[DllImport(kernel32, SetLastError=true)]

public static extern int /*stdcall*/ GetCPInfo(

                          uint CodePage,

                          ref _cpinfo lpCPInfo);

 

 

 

 

The function is called in Delphi with:

 

var

  AnsiCPInfo: TCPInfo;

 

GetCPInfo(CP_ACP, AnsiCPInfo);

 

and in C# with:

 

_cpinfo AnsiCPInfo = _cpinfo.CreateRecord();

GetCPInfo((uint) CP_ACP, ref AnsiCPInfo);

 

 

A special case are character arrays like in the _OSVERSIONINFOW record:

 

    szCSDVersion: array[0..127] of WideChar; { Maintenance UnicodeString for PSS usage }

 

This is converted to:

 

  [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string szCSDVersion; /* Maintenance AnsiString for PSS usage */

 

 

 

 

 

 

 

 

 

 

 

 



This page belongs to the Delphi2C# Documentation

Delphi2C# home  Content