在编写组件程序时,经常会使用CoCreateInstance直接取COM组件的接口,非常方便,那CoCreateInstance到底干了些什么事呢?1、CoCreateInstance取COM组件的接口的基本流程
//参数:rclsid = 组件CLSID
//参数:riid = 接口ID
WINOLEAPI CoCreateInstance(REFCLSID rclsid, LPUNKNOWN pUnkOuter,
DWORD dwClsContext, REFIID riid, LPVOID FAR* ppICOMInterface)
{
//根据组件的CLSID从注册表中取Dll的地址,并加载
char pszCOMDllPath;
SHGetValue(HKEY_CLASSES_ROOT, "CLSID+rclsid\InprocServer32", "默认", pszCOMDllPath);
LoadLibrary(pszCOMDllPath);
//调用DllGetClassObject,创建IID_IClassFactory总接口
IClassFactory* pIFactory;
DllGetClassObject(rclsid, IID_IClassFactory, &pIFactory);
{
IClassFactory* pITotalFactory = new IClassFactory;
pITotalFactory->QueryInterface(IID_IClassFactory, &pIFactory);
}
//调用CreateInstance创建COM总接口对象
pIFactory->CreateInstance(pUnkOuter, riid, ppICOMInterface);
{
ICOMInterface* pITotalCOMInterface = new ITotalCOMInterface;
//根据接口IID取指定接口对象
pITotalCOMInterface->QueryInterface(riid, ppICOMInterface);
}
}