使用CoCreateInstance方法时出现问题

时间:2017-10-31 09:58:10

标签: c++ winapi com windows-services atl

我想测试COM Service(EXE),但我无法从HRESULT检索正确的CoCreateInstance

我的COM示例是'ATLCOMService' Microsoft示例。如何解决?

客户端代码是:

    void main()
    {
        HRESULT         hr;
        ISimpleObject *IFirstATL = NULL;

        hr = CoInitialize(0);
        if (SUCCEEDED(hr))
        {
            hr = CoCreateInstance(CLSID_SimpleObject, NULL,
                CLSCTX_LOCAL_SERVER,
                LIBID_ATLCOMServiceLib, (void**)&IFirstATL);
            //hr is: E_NOINTERFACE No such interface supported.

            hr = CoCreateInstance(CLSID_SimpleObject, NULL,
                CLSCTX_INPROC_SERVER,
                LIBID_ATLCOMServiceLib, (void**)&IFirstATL);
            //hr is: REGDB_E_CLASSNOTREG Class not registered

            if (SUCCEEDED(hr))
            {
                BSTR str;
                IFirstATL->HelloWorld(&str);
                cout << str << endl;

                IFirstATL->Release();
            }
            else
            {
                cout << "CoCreateInstance Failed." << endl;
            }
        }
        CoUninitialize();
    }

头文件中的ID是:

    #ifndef CLSID_DEFINED
    #define CLSID_DEFINED
    typedef IID CLSID;
    #endif // CLSID_DEFINED

    #define MIDL_DEFINE_GUID(type,name,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) \
            const type name = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}}

    #endif !_MIDL_USE_GUIDDEF_

    MIDL_DEFINE_GUID(IID, 
    IID_ISimpleObject,0x1B877090,0x76CD,0x4EDE,0x81,0x15,0xEC,
    0x4C,0xCD,0x96,0x76,0xF3);


    MIDL_DEFINE_GUID(IID, LIBID_ATLCOMServiceLib,0xCC2CA6F0,0x2220,0x4D77,0xBA,
    0x46,0x4B,0xCB,0x62,0x15,0x6A,0x28);


    MIDL_DEFINE_GUID(IID, DIID__ISimpleObjectEvents,0x7DACF5E9,0x2885,0x4E4E,
    0x83,0xDD,0xCA,0x6C,0xC3,0xA8,0x8B,0x6D);


    MIDL_DEFINE_GUID(CLSID, 
    CLSID_SimpleObject,0x388F1C82,0xED00,0x4966,0x95,0x90,
    0x02,0xF6,0xB9,0xCC,0xA4,0x1B);

    #undef MIDL_DEFINE_GUID

    #ifdef __cplusplus
    }
    #endif

在下面看到了注册表实例和服务状态:

注册表 - CLSID:

Registry - CLSID

注册表 - typeid:

Registry - typeid

和 服务状态:

Service status

1 个答案:

答案 0 :(得分:2)

       hr = CoCreateInstance(CLSID_SimpleObject, 
            NULL,
            CLSCTX_LOCAL_SERVER,
            LIBID_ATLCOMServiceLib, // <<--- IID_ISimpleObject here?
            (void**)&IFirstATL);
        //hr is: E_NOINTERFACE No such interface supported.

请注意,第四个参数应该是您请求的接口的IID,大概是IID_ISimpleObject。 API返回的错误代码建议您检查是否请求了正确的接口:E_NOINTERFACE(或者如果它是正确的,那么服务器可能错误地没有实现它,或者它是一个编组问题)。 / p>