C++ DLL: "MyDll.dll"
typedef HRESULT (CALLBACK * CALLBACKPROC)(DWORD wEvent,LONG_PTR arg,PVOID pParam);
CALLBACKPROC g_pCallback = NULL;
LPVOID g_pCallbackParam = NULL;
EXTERN_C VOID __declspec(dllexport) WINAPIV SetCallback(CALLBACKPROC _proc,LPVOID pParam)
{
g_pCallback = _proc;
g_pCallbackParam = pParam;
}
#define SOMEDLLMETHOD_EVENT_ID 0x01
EXTERN_C VOID __declspec(dllexport) WINAPIV SomeDllMethod()
{
if (g_pCallback) g_pCallback(SOMEDLLMETHOD_EVENT_ID,(LONG_PTR)"some argument",g_pCallbackParam);
}
type
TDllWrapper = class
protected
FOnDllEvent: TNotifyEvent;
m_hDll: HMODULE;
protected
function OnCallbackEvent(wEvent:DWORD;arg:Pointer):HRESULT; virtual;
public
procedure CallSomeDllMethod();
public
constructor Create;
destructor Destroy;
published
property OnDllEvent: TNotifyEvent read FOnDllEvent write FOnDllEvent;
end;
type
TCALLBACKPROC = function(wEvent:DWORD;arg:Pointer;pParam:Pointer):HRESULT stdcall;
type
TSetCallbackFunc = procedure(_proc:TCALLBACKPROC;pParam:Pointer) cdecl;
const SOMEDLLMETHOD_EVENT_ID = $01;
function CallbackProc(wEvent:DWORD;arg:Pointer;pParam:Pointer):HRESULT stdcall;
begin
result := 0;
if (pParam <> nil) then result := TDllWrapper(pParam).OnCallbackEvent(wEvent,arg);
end;
constructor TDllWrapper.Create;
var
fnSetCallback:TSetCallbackFunc;
begin
inherited Create;
m_hDll := LoadLibrary('MyDll.dll');
fnSetCallback := GetProcAddress(m_hDll,'SetCallback');
fnSetCallback(CallbackProc,self);
end;
destructor TDllWrapper.Destroy;
var
fnSetCallback:TSetCallbackFunc;
begin
fnSetCallback := GetProcAddress(m_hDll,'SetCallback');
fnSetCallback(nil,nil);
FreeLibrary(m_hDll);
inherited Destroy;
end;
function TDllWrapper.OnCallbackEvent(wEvent:DWORD;arg:Pointer):HRESULT;
begin
result := 0;
if (wEvent = SOMEDLLMETHOD_EVENT_ID) then
begin
if Assigned(FOnDllEvent) then FOnDllEvent(self);
end;
end;
procedure TDllWrapper.CallSomeDllMethod();
var
fnSomeDllMethod:procedure() cdecl;
begin
fnSomeDllMethod := GetProcAddress(m_hDll,'SomeDllMethod');
fnSomeDllMethod();
end;
type
TMainForm = class(TForm)
m_MyDll:TDllWrapper;
procedure OnDllEventCallback(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
end;
procedure TMainForm.OnDllEventCallback(Sender: TObject);
begin
OutputDebugString('Our callback event called');
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
m_MyDll:= TDllWrapper.Create;
m_MyDll.OnDllEvent := OnDllEventCallback;
m_MyDll.CallSomeDllMethod;
end;
procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
m_MyDll.Free;
end;
[edit]code block added[/edit]