Sometimes you need to pass a procedure address to a Windows API, but you
would rather pass a method instead. In such a situation the function
"MethodToProcedure" can come in handy. You enter a method address and your
current "Self" value and you get a procedure address as the result, which you
then can pass to a Windows API.
Please note that this works only for *stdcall* methods! Don't use it for
any other calling convention! (But since almost all Windows APIs are stdcall,
this should not be a big problem.)
After you don't need the procedure pointer anymore, please free it with
"VirtualFree".
|
function MethodToProcedure (self : TObject;
methodAddr : pointer) : pointer; overload;
function MethodToProcedure (method : TMethod) : pointer; overload;
|
|
Here comes a little example which demonstrates a correct and useful usage of
"MethodToProcedure":
|
unit EnumWindows;
interface
implementation
uses Windows, SysUtils, madTools;
type
TEnumWindows = class
private
function EnumCallbackMethod(window: dword; lParam: integer) : bool; stdcall;
public
constructor Create;
end;
constructor TEnumWindows.Create;
var EnumCallbackProc : pointer;
begin
inherited;
EnumCallbackProc := MethodToProcedure(Self, @TEnumWindows.EnumCallbackMethod);
EnumWindows(EnumCallbackProc, 0);
VirtualFree(EnumCallbackProc, 0, MEM_RELEASE);
end;
function TEnumWindows.EnumCallbackMethod(window: dword; lParam: integer) : bool; stdcall;
begin
result := true;
[...]
end;
end.
|
|