Windows API functions are declared in structured programming style.
For example consider classical example of using critical sections:
procedure Test;
var
CS: TCriticalSection;
begin
InitializeCriticalSection(CS);
try
EnterCriticalSection(CS);
try
//somecode
finally
LeaveCriticalSection(CS);
end;
finally
DeleteCriticalSection(CS);
end;
end;
Now consider the example rewritten in object-oriented Windows API:
procedure Test;
var
NewCS: TNewCriticalSection;
begin
NewCS.Initialize;
try
NewCS.Enter;
try
//somecode
finally
NewCS.Leave;
end;
finally
NewCS.Delete;
end;
end;
Bespoke the code is easier to read, the benefit is CodeInsight works nicely — type "NewCS." and press Control+Space…
Below unit implements new object-oriented Windows API:
unit NewWindows;
interface
uses Windows;
{$HINTS OFF}
type
TNewCriticalSection = object
private
FOldCriticalSection: TRTLCriticalSection;
public
procedure Initialize; stdcall;
procedure Delete; stdcall;
procedure Enter; stdcall;
procedure Leave; stdcall;
end;
{$HINTS ON}
implementation
procedure TNewCriticalSection.Initialize;
external kernel32 name 'InitializeCriticalSection';
procedure TNewCriticalSection.Delete;
external kernel32 name 'DeleteCriticalSection';
procedure TNewCriticalSection.Enter;
external kernel32 name 'EnterCriticalSection';
procedure TNewCriticalSection.Leave;
external kernel32 name 'LeaveCriticalSection';
end.
The trick is that Delphi object types are passed by value, hence when calling TNewCriticalSection.Initialize method, FOldCriticalSection field is occupying on the stack the same place argument of InitializeCriticalSection would do. Thus we can declare implementation of TNewCriticalSection.Initialize as external from kernel32.dll.
Comments
Post new comment