Mirror

Attaching to COM from a DLL (Views: 101)

Problem/Question/Abstract:

When attaching to a COM object in a DLL an error occurs if CoInitialize() has not been called. It is also required to call CoUnInitialize(). The easiest way to do this is in the initialization and ExitProc() routines of the DLL. The following example demonstrates how to attach to COM from your DLL.

Answer:

library TestCom;

uses ActiveX, SysUtils, Classes, ComObj;

var
SaveExit: Pointer; // Required by Exit routine

// ============================
// Arbitary test code
// ============================

procedure RunDll(Key: PChar); stdcall;
var
DMess, WKey: WideString;
OServer: OleVariant;
KeyName: WideString;
begin
try
// Connect to COM
OServer := CreateOleObject('PeekaBooAlerter.TPBbase');
KeyName := 'Wakeup Message';
OServer.ReadStringKey(KeyName, DMess);
WKey := string(Key);
OServer.WriteAlert(DMess, WKey);
finally
OServer := VarNull; // Release the COM attachment
end;
end;

// =================================================
// EXIT Routine - Deinitialize COM library and call
// original Exit routine
// =================================================

procedure LibExit;
begin
// library exit code
CoUnInitialize;
ExitProc := SaveExit; // restore exit procedure chain
end;

// ==================================================
// Export declarations
// ==================================================

exports
RunDll index 1,

// ==================================================
// DLL library initialization code
// ==================================================

begin
CoInitialize(nil);
SaveExit := ExitProc; // Save exit procedure chain
ExitProc := @LibExit; // Install LibExit exit procedure
end.


<< Back to main page