Wednesday, November 19, 2008

DLL Based - In-Proc COM Server


An In-Process server is a COM library that gets loaded into your program at run-time. In other words, it's a COM object in a Dynamic Link Library (DLL). A DLL isn't really a server in the traditional sense, because it loads directly into the client's address space. If you're familiar with DLLs, you already know a lot about how the COM object gets loaded and mapped into the calling program.

Normally a DLL is loaded when LoadLibrary() is called. In COM, you never explicitly call LoadLibrary(). Everything starts automatically when the client program calls CoCreateInstance(). One of the parameters to CoCreateInstance is the GUID of the COM class you want. When the server gets created at compile time, it registers all the COM objects it supports. When the client needs the object, COM locates the server DLL and automatically loads it. Once loaded, the DLL has a class factory to create the COM object.

CoCreateInstance() returns a pointer to the COM object, which is in turn used to call a method (in the example described here, the method is called Beep().) A nice feature of COM is that the DLL can be automatically unloaded when it's not needed. After the object is released and CoUninitialize() is called, FreeLibrary() will be called to unload the server DLL.

If you didn't follow all that, it's easier than it sounds. You don't have to know anything about DLL's to use COM. All you have to do is call CoCreateInstance(). One of the advatages of COM is that it hides these details so you don't have to worry about this type of issue.

There are advantages and disadvantages to In-process COM servers. If dynamic linking is an important part of your system design, you'll find that COM offers an excellent way to manage DLL's. Some experienced programmers write all their DLL's as In-process COM servers. COM handles all the chores involved with the loading, unloading, and exporting DLL functions and COM function calls have very little additional overhead.

Our main reason for selecting an In-process server is somewhat more prosaic: It makes the example simpler. We won't have to worry about starting remote servers (EXE or service) because our server is automatically loaded when needed. We also avoid building a proxy/stub DLL to do the marshalling.

Unfortunately, because the In-Process server is so tightly bound to our client, a number of the important "distributed" aspects of COM are not going to be exposed. A DLL server shares memory with it's client, whereas a distributed server would be much more removed from the client. The process of passing data between a distributed client and server is called marshaling. Marshaling imposes important limitations on COM's capabilities that we won't have to worry about with an in-proc server.

0 comments: