Programmatically registering and unregistering COM servers

In certain situations, there may be a need to programmatically register or unregister a COM server
given just the name of the module that actually implements it. The specified server could be an
InProcess COM server or an OutOfProcess COM server. As we all know, inprocess COM servers are
registered by loading the DLL module and invoking the exported function DllRegisterServer().
The unregistration operation is performed by invoking DllUnregisterServer() instead.

OutOfProcess COM servers are registered by passing /REGSERVER on the command line for that executable.
The corresponding unregistration is done by passing /UNREGSERVER on the command line. Given this,
the only thing left is to detect if the file passed in is a DLL or an EXE.
This is easily achieved by using the GetFileVersionInfo() Platform SDK function.

I have written a C++ function to achieve all of this and the code for the same follows. This code uses
MFC but can be easily rewritten using std::basic_string() to make it usable within a pure ATL project.

Comments

Can't Rely on Version Resource!

There is a real problem attempting to identify the COM server as inproc
or outproc based on the version resource information. The most common
problem will be found with process images that have no resource. Not
likely? Unfortunately, proxy-stubs are generated without version
resources (I suppose to make them as lightweight as possible?)

Another problem seen is where a version resource misidentifies the
image. Since the version resource is for informational as opposed to
operational purposes, there is no obligation for accuracy! As an
example, this could happen when an inproc server is converted to
outproc but the version resource is not updated appropriately.

What to do? Simply try loading the file as an inproc server and see
what happens. If that fails, try running it as an outproc server. No
harm in trying, as they say.

Here's an example based on Jeremiah Talkar's original RegisterOleServer
function: