Author: Mike Heydon
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:
1 library TestCom;
2 3 uses ActiveX, SysUtils, Classes, ComObj;
4 5 var6 SaveExit: Pointer; // Required by Exit routine7 8 // ============================9 // Arbitary test code10 // ============================11 12 procedure RunDll(Key: PChar); stdcall;
13 var14 DMess, WKey: WideString;
15 OServer: OleVariant;
16 KeyName: WideString;
17 begin18 try19 // Connect to COM20 OServer := CreateOleObject('PeekaBooAlerter.TPBbase');
21 KeyName := 'Wakeup Message';
22 OServer.ReadStringKey(KeyName, DMess);
23 WKey := string(Key);
24 OServer.WriteAlert(DMess, WKey);
25 finally26 OServer := VarNull; // Release the COM attachment27 end;
28 end;
29 30 // =================================================31 // EXIT Routine - Deinitialize COM library and call32 // original Exit routine33 // =================================================34 35 procedure LibExit;
36 begin37 // library exit code38 CoUnInitialize;
39 ExitProc := SaveExit; // restore exit procedure chain40 end;
41 42 // ==================================================43 // Export declarations44 // ==================================================45 46 exports47 RunDll index 1,
48 49 // ==================================================50 // DLL library initialization code51 // ==================================================52 53 begin54 CoInitialize(nil);
55 SaveExit := ExitProc; // Save exit procedure chain56 ExitProc := @LibExit; // Install LibExit exit procedure57 end.