加载接口失败

Loading an interface fails

本文关键字:失败 接口 加载      更新时间:2023-10-16

我想使用COM函数:CreateInstancehttp://msdn.microsoft.com/en-us/library/k2cy7zfz%28v=vs.80%29.aspx

这样的

IPointer p=NULL;
HRESULT hr=p.CreateInstance(xxx);

但是我没有xxxCLSID,我只知道它的接口名称ISubPointer当我用oleview查看文件时,我可以在tlb文件中看到它的接口描述。如何使用CreateInstance呢?

有两种方法:

1: a ClassFactory,and

第二个:创建指针的辅助函数

我发现了这个:

int main()
{
    IMath* pIMath;
    HRESULT hr;
    // 1. Initialize COM Library
    CoInitialize(NULL);
    // 2. Call CoCreateInstance to get the IMath interface pointer
    hr = CoCreateInstance ( __uuidof(CMathComp), NULL, CLSCTX_INPROC_SERVER,
                            __uuidof(IMath), (void**) &pIMath );
    if ( FAILED(hr) )
    {
        return 0;
    }
    // 3. Call the interface functions
    int sum = pIMath->Add(1, 3);
    printf("Sum = %d n", sum);
    int sub = pIMath->Sub(4, 3);
    printf("Sub = %d n", sub);
    // 4. Release the interface pointer if you are done
    pIMath->Release();
    // 5. Un-Initialize COM Library
    CoUninitialize();
    return 0;
}

另见MSDN:

HRESULT CoCreateInstance(
  _In_   REFCLSID rclsid,
  _In_   LPUNKNOWN pUnkOuter,
  _In_   DWORD dwClsContext,
  _In_   REFIID riid,
  _Out_  LPVOID *ppv
);

如果您可以从OLEVIEW收集CLSID,请使用它,否则必须有关于此的文档。如果不暴露list CLSID,就无法交付组件。

您有两个选项来获取您想要创建的对象的类ID。您可以使用OLE Viewer来生成头文件,也可以使用#import指令直接将类型库导入源文件。您所引用的CreateInstance函数是_com_ptr_t的非静态成员,并且要求您使用它的一个实例。

下面的例子应该能帮到你。

#include <comip.h>  // _com_ptr_t
#import "tlbname.tlb" // Change to the name of your type library

int main()
{
    CoInitialize(NULL);
    ::_com_ptr_t<ISubPointer>   ptr;
    // CoISubPointer is the class ID specified in the type library
    // you will need to change the name accordingly.
    ptr.CreateInstance(__uuid(CoISubPointer), NULL, CLSCTX_INPROC_SERVER);
    CoUninitialize();
    return 0;
 }

main()完成后,ptr将自动释放它对ISubPointer对象的引用。

不知道类ID就不能创建COM对象。我建议阅读本文中的COM基础知识http://www.codeproject.com/Articles/633/Introduction-to-COM-What-It-Is-and-How-to-Use-It