windows 在同一台机器上创建对象时,CoCreateInstance() 和 CoGetClassObject() 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/824907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 12:24:09  来源:igfitidea点击:

What's the difference between CoCreateInstance() and CoGetClassObject() when creating objects on the same machine?

windowscominteropcom-interop

提问by sharptooth

I understand that CoCreateInstance finds the COM server for the given class id, creates the object instance for that id and retrieves an interface from that object instance. CoGetClassObject() finds the COM server for the class id, creates an instance of the class factory for that class id and retrieves that class factory interface which can be then used for creating actual objects.

我知道 CoCreateInstance 为给定的类 id 找到 COM 服务器,为该 id 创建对象实例并从该对象实例中检索接口。CoGetClassObject() 找到类 id 的 COM 服务器,为该类 id 创建类工厂的实例,并检索该类工厂接口,然后可用于创建实际对象。

How else do these functions differ when used to create objects on the same machine? Do they work the same way but only cause different code to be invoked in the exactly same COM server?

当用于在同一台机器上创建对象时,这些函数还有什么不同?它们是否以相同的方式工作,但只会导致在完全相同的 COM 服务器中调用不同的代码?

回答by JaredPar

CoGetClassObject essentially returns you a pointer to a factory for a particular interface. Under the hood, CoCreateInstance uses CoGetClassObject. The advantage of calling CoGetClassObject is that it allows you to only have to create the class factory once if you want to create many instances of a particular object.

CoGetClassObject 本质上会返回一个指向特定接口工厂的指针。在幕后,CoCreateInstance 使用 CoGetClassObject。调用 CoGetClassObject 的优点是,如果您想创建特定对象的多个实例,则只需创建一次类工厂。

The MSDN section on CoGetClassObject has a brief discussion on how you can take advantage of this functionality.

CoGetClassObject 的 MSDN 部分简要讨论了如何利用此功能。

回答by byte

One scenario in addition to what JaredPar said - CoGetClassObject returns you a class factory (calls DLLGetClassObject exported function of your DLL in case of inproc server). Class factory is used to instantiate coclass. CoCreateInstance internally calls CoGetClassObject, gets the required class factory and then uses it to instantiate the coclass you requested. When calling CoCreateInstance, you cannot delay creation of the coclass. There are times when creation of coclass could be expensive and you would want to delay its creation but still have access to the class factory so you could instantiate the coclass on demand.

除了 JaredPar 所说的一个场景 - CoGetClassObject 返回一个类工厂(在 inproc 服务器的情况下调用你的 DLL 的 DLLGetClassObject 导出函数)。类工厂用于实例化coclass。CoCreateInstance 内部调用 CoGetClassObject,获取所需的类工厂,然后使用它来实例化您请求的 coclass。调用 CoCreateInstance 时,不能延迟创建 coclass。有时创建 coclass 可能很昂贵,您可能希望延迟它的创建,但仍然可以访问类工厂,以便您可以根据需要实例化 coclass。