Tuesday, November 30, 2004

Keeping out-of-proc automation servers alive

I know, out-of-proc automation servers aren't very popular in these days when you have COM+ and .NET. But if you're still a person writing out of proc automation servers, (like Microsoft is with Word, Excel and the whole lot) you might need to consider a small fact.

Delphi assumes that if your EXE was already running when a COM call was made to an object hosted inside it, then AFTER that call finishes, Delphi keeps your application running. (Obviously, I guess) But if your EXE isn't already running, then a COM call will *instantiate* your EXE, and create the COM object. Fine. But after the COM object is released, your EXE shuts down!!!!

This is because of some code in ComServ.pas that's specific to automation - it actually checks if your EXE was launched through Automation (i.e. with a /AUTOMATION or /EMBEDDING parameter) and if so, when your object is released, it clears a reference to the factory. The Windows COM subsystem maintains references to the object factory in your application...and when that count reaches zero, COM assumes your factory has bid it goodbye, and in subsequent calls, will create a NEW instance of your application.

So if you want to be able to say "I don't care how my EXE is launched but once it's launched I want the same EXE to handle all subsequent calls to the COM objects I host.", then read on. (If you're totally confused by now, stop.)

What you need to do, is to trick COM into thinking your object factory is still alive. So, in some global create code (maybe in a form create event in an autocreated form, or a constructor of a global object) add this:

ComObj.CoAddRefServerProcess;

and in the corresponding destructor or FormDestroy, add:

ComObj.CoReleaseServerProcess;

(obviously, use ComObj.)

0 Comments:

Post a Comment

<< Home