CoCreateInstance挂起在单线程exe COM客户端中

CoCreateInstance hangs in single-threaded exe COM client

本文关键字:COM 客户端 exe 单线程 挂起 CoCreateInstance      更新时间:2023-10-16

我正在学习COM的基础知识。现在我正在编写进程外服务器。我写了相当基本的服务器应用程序,dll/stub和客户端应用程序。

若我注册服务器并在进程中使用CoCreateInstance创建对象的实例,它就可以工作:

服务器/客户端:

int _tmain(int argc, _TCHAR* argv[])
{
    IClassFactory *factory = new ISimpleServerFactory();
    DWORD classToken;
    ::CoInitialize(NULL);
    CoRegisterClassObject(
        IID_ISimpleServer, 
        factory, 
        CLSCTX_LOCAL_SERVER, 
        REGCLS_MULTIPLEUSE, 
        &classToken);
    ISimpleServer *pISimpleServer = NULL;
    HRESULT hr = CoCreateInstance(
        CLSID_CSimpleServer, 
        NULL, 
        CLSCTX_LOCAL_SERVER, 
        IID_ISimpleServer,
        (void **)&pISimpleServer);           //<===========SUCCESS
    if(SUCCEEDED(hr))
        printf("Instantiation successfuln");
    if(pISimpleServer != NULL)
        pISimpleServer->Release();
    std::cin.ignore();
    CoRevokeClassObject(classToken);
    ::CoUninitialize();
    return 0;
}

现在我尝试将其拆分为单独的应用程序:

服务器:

int _tmain(int argc, _TCHAR* argv[])
{
    IClassFactory *factory = new ISimpleServerFactory();
    DWORD classToken;
    ::CoInitialize(NULL);
    CoRegisterClassObject(
        IID_ISimpleServer, 
        factory, 
        CLSCTX_LOCAL_SERVER, 
        REGCLS_MULTIPLEUSE, 
        &classToken);
    if(SUCCEEDED(hr))
        printf("Instantiation successfuln");
    if(pISimpleServer != NULL)
        pISimpleServer->Release();
    std::cin.ignore();
    CoRevokeClassObject(classToken);
    ::CoUninitialize();
    return 0;
}

客户:

int _tmain(int argc, _TCHAR* argv[])
{
    CoInitialize(NULL);
    SimpleServer::ISimpleServer *pISimpleServer = NULL;
    HRESULT hr = CoCreateInstance(
        CLSID_CSimpleServer, 
        NULL, 
        CLSCTX_LOCAL_SERVER, 
        IID_ISimpleServer,
        (void **)&pISimpleServer);       // HERE IT HANGS
    if (SUCCEEDED(hr))
    {
        //*****SMTH***
    }
    else
    {
        printf("Failed to load COM object (server not loaded?)n");
    }
    if(pISimpleServer != NULL)
        pISimpleServer->Release();
    CoUninitialize();
    std::cin.ignore();
    return 0;
}

客户端挂起运行。如果服务器没有启动,客户端会键入"加载COM对象失败(服务器没有加载?)",所以我认为这不是服务器注册的问题。

但那会是什么呢?

好吧,就像Raymond指出的那样,我的服务器没有发送消息。我添加了

MSG msg;
while (GetMessage(&msg, 0, 0, 0) > 0) 
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);
    if(_kbhit())
        break;
}

进入服务器主体,它变得更好:)