Can I create and use a COM class without registering it in the registry?

前端 未结 2 1749
借酒劲吻你
借酒劲吻你 2021-01-07 08:02

I need to make a custom COM object that is going to end up looking similar to this:

static const GUID IID_ClientCommunicator = { 0x5219b44a, 0x874, 0x449e,{          


        
相关标签:
2条回答
  • 2021-01-07 08:23

    It is the job of an object that implements IClassFactory to construct the class.

    You already have your CLSID_ClientCommunicator. Now you just need to supply an IClassFactory object that can construct it:

    private class ClientCommunicatorFactory : ComObject, IClassFactory
    {
       //IClassFactory methods
       HRESULT CreateInstance(IUnknown unkOuter, Guid iid, out obj)
       {
          ClientCommunicator cc = new CClientCommunicator();
    
          HRESULT hr = cc.QueryInterface(iid, out obj);
          return hr;
       }
    }
    

    You now have:

    • your CLSID_ClientCommunicator
    • your IClassFactory that can construct it

    You register the two with COM using CoRegisterClassObject:

    IClassFactory factory = new ClientCommunicatorFactory();
    DWORD dwCookie; //cookie to keep track of our registration
    
    CoRegisterClassObject(
       CLSID_ClientCommunicator,  // the CLSID to register
       factory,                   // the factory that can construct the object
       CLSCTX_INPROC_SERVER,      // can only be used inside our process
       REGCLS_MULTIPLEUSE,        // it can be created multiple times
       out dwCookie               // cookie we can later use to delete the registration
    );
    

    So now, if someone in your process tries to construct your class:

    IUnknown cc = CreateComObject(CLSID_ClientCommunicator);
    

    it will just work; even though the class is not registered in the registry.

    Bonus

    IUnknown CreateComObject(Guid clsid)
    {
       IUnknown unk;
       HRESULT hr = CoCreateInstance(clsid, null, CLSCTX_INPROC_SERVER, IID_IUnknown, out unk);
       if (Failed(hr))
          throw new EComException(hr);
    
       return unk;
    }
    
    0 讨论(0)
  • 2021-01-07 08:27

    As user @RaymondChen pointed out in the comments there is a function CoRegisterClassObject here, which can be used to register COM classes without needed to add them to the registry.

    This of course only allows you to use that COM class in the scope of the executable which registered it.

    0 讨论(0)
提交回复
热议问题