17

Is it possible to use COM Object from DLL without register in C++ not managed code?

EOG
  • 1,677
  • 2
  • 22
  • 36

3 Answers3

11

Yes, if it does not rely internally on other registered objects.

  1. You LoadLibrary the DLL
  2. You GetProcAddress its DllGetClassObject
  3. You call DllGetClassObject to obtain IClassFactory pointer for CLSID of interest
  4. You are good to go with IClassFactory::CreateInstance and instantiate the coclass
Roman R.
  • 68,205
  • 6
  • 94
  • 158
  • 6
    2 ½. Make sure you're in the correct apartment before calling `DllGetClassObject`. Even so, you won't get marshaling for the specific object model interfaces. Even if the C++ COM objects implement `IMarshal` or `IProvideClassInfo` themselves, you'll need to do the same if you're the one providing objects that implement any of those interfaces (e.g. event dispinterfaces). For these reasons and many other, this is bad practice. You should use registration free COM instead. – acelent Feb 05 '15 at 00:18
8

You can create manifest files for the DLL and use Registration-Free COM.

Sergey Podobry
  • 7,101
  • 1
  • 41
  • 51
5

Say, the COM DLL needs to be registered, but the application doesn't have admin access rights. Here is an easy hack to register the DLL under HKEY_CURRENT_USER, which doesn't require admin rights:

  1. Use LoadLibrary to load the COM DLL.
  2. Call GetGetProcAddress to get the address of DllRegisterServer.
  3. Call RegOverridePredefKey to make the temporary registry redirects: HKEY_LOCAL_MACHINE to HKEY_CURRENT_USER and HKEY_CLASSES_ROOT to HKEY_CURRENT_USER\Software\Classes.
  4. Call DllRegisterServer obtained in step 2.
  5. Reverse the registry redirects.
  6. Use the COM server as usual, it's now registered under HKEY_CURRENT_USER.
noseratio
  • 59,932
  • 34
  • 208
  • 486
  • 2
    "easy" hack. Clever though. – Dmytro Sep 04 '16 at 15:35
  • The [`RegOverridePredefKey`](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regoverridepredefkey) documentation says that the new `HKEY` cannot be one of the predefined keys, so I'm not sure how to proceed with step 3. Should I open an existing registry key then? – phetdam Apr 27 '23 at 18:44
  • I ended up using an answer [for another thread](https://stackoverflow.com/a/44416524/14227825) and had success calling [`OaEnablePerUserTLibRegistration`](https://learn.microsoft.com/en-us/windows/win32/api/oleauto/nf-oleauto-oaenableperusertlibregistration) before `DllRegisterServer`. Only needed to map `HKEY_CLASSES_ROOT` to `HKEY_CURRENT_USER\Software\Classes`. I might be missing something however. – phetdam Apr 27 '23 at 19:10