Data Types

Most data types do not need to be changed, except for pointer and string types. The following table shows commonly used data types, and how to translate them for managed code:

Unmanaged Data Type

Managed Data Type

Input Parameter

Output Parameter

Pointer to string (PChar)



Untyped parameter/buffer



Pointer to structure (PRect)

const TRect

var TRect

Pointer to simple type (PByte)

const Byte

var Byte

Pointer to array (PInteger)

array of Integer

array of Integer

Pointer to pointer type (APInteger)IntPtr


IntPtr can also represent all pointer and string types, in which case you need to manually marshal data using the Marshal class. When working with functions that receive a text buffer, the StringBuilder class provides the easiest solution. The following example shows how to use a StringBuilder to receive a text buffer:

function GetText(Window: HWND; BufSize: Integer = 1024): string; var

Buffer: StringBuilder; begin

Buffer := StringBuilder.Create(BufSize); GetWindowText(Window, Buffer, Buffer.Capacity); Result := Buffer.ToString; end;

The StringBuilder class is automatically marshaled into an unmanaged buffer and back. In some cases it may not be practical, or possible, to use a StringBuilder. The following examples show how to marshal data to send and retrieve strings using SendMessage:

procedure SetText(Window: HWND; Text: string); var

Buffer: IntPtr; begin

Buffer := Marshal.StringToHGlobalAuto(Text); try

Result := SendMessage(Window, WM_SETTEXT, 0, Buffer); finally


An unmanaged buffer is allocated, and the string copied into it by calling StringToHGlobalAuto. The buffer must be freed once it's no longer needed. To marshal a pointer to a structure, use the Marshal. StructureToPtr method to copy the contents of the structure into the unmanaged memory buffer.

The following example shows how to receive a text buffer and marshal the data into a string:

function GetText(Window: HWND; BufSize: Integer = 1024): string; var

Buffer: IntPtr; begin

Buffer := Marshal.AllocHGlobal(BufSize * Marshal.SystemDefaultCharSize); try

SendMessage(Window, WM_GETTEXT, BufSize, Buffer); Result := Marshal.PtrToStringAuto(Buffer); finally

Marshal.FreeHGlobal(Buffer); end; end;

It is important to ensure the buffer is large enough, and by using the SystemDefaultCharSize method, the buffer is guaranteed to hold BufSize characters on any system.

Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook

Post a comment