The most elegant way to encapsulate WinAPI callbacks inside a class

I am thinking of an elegant way to encapsulate WinAPI callbacks inside a class. Suppose I handle asynchronous class I / O. All Windows callbacks should be stdcall functions, not class methods (for example, I need to pass their addresses to the ReadFileEx WinAPI function). Thus, I cannot just pass method addresses as callback procedures for WinAPI functions.

What is the most elegant way to encapsulate the functionality of this type inside a class, so the class has OnReadCompleted and OnWriteCompleted events (I use Delphi as the main language, but I assume that in C ++ the situation should be the same because the class methods are different from simple methods by the fact that the first hidden parameter is a link, of course, this class is nothing and there can be many of them created by the application at the same time.

What do you think would be a good way to implement this?

+3
source share
2 answers

, , IMO, winapi. , , VCL classes.MakeObjectInstance, . . , OO .

+4

. Delphi.

:

type
  TMyThread = class
  private
    // ...

    class function ThreadProc(Param: Pointer): DWord; stdcall; static; // <- WinAPI call back

    function Execute: DWord; // <- actual callback
  public
    constructor Create;
    // ...
  end;

{ TMyThread }

constructor TMyThread.Create;
begin
  // ...
  FHandle := CreateThread(nil, 0, @ThreadProc, Self, 0, FID);
end;

class function TMyThread.ThreadProc(Param: Pointer): DWord;
begin
  Result := TMyThread(Param).Execute;
end;

function TMyThread.Execute: DWord;
begin
  MessageBox(0, 'Hello from thread', 'Information', MB_OK or MB_ICONINFORMATION);
  Result := 0;
end;

: ThreadProc - WinAPI. , "". . (Execute), .

+2

Source: https://habr.com/ru/post/1748040/


All Articles