c++ - CComPtr CoCreateInstance 返回 0x80070582(类已存在。)

标签 c++ com atl smart-pointers

当用户按下登录按钮时调用 StartComObjects 函数,当用户按下取消按钮时调用 StopComObjects 函数。 StartComObjects 函数使用 CComPtr.CoCreateInstance 创建 COM 对象并使用 AfxConnectionAdvise 设置一些连接点。当用户按下“取消”按钮时,使用 AfxConnectionUnadvise 断开连接点,并且在调用 CComPtr 上的 Release 之前停止 COM 对象。

当我第二次按下登录按钮时,CComPtr.CoCreateInstance 返回 0x80070582(类已存在)。这可以防止在第二次调用 StartComObjects 时创建 COM 对象。我不确定为什么这不起作用。 CComPtr::Release 不应该释放 COM 对象并允许我在旧对象停止后创建一个新对象吗?有什么办法可以解决这个问题吗?

最佳答案

这是 Windows 错误(设备 7,错误代码 1410),由 RegisterClass(Ex) 引起。此示例代码再现了它:

#include "stdafx.h"
#include <windows.h>
#include <assert.h>

int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE, LPTSTR, int)
{
    WNDCLASSEX wcex = { sizeof(WNDCLASSEX) };
    wcex.style = CS_HREDRAW | CS_VREDRAW;
    wcex.hInstance = hInstance;
    wcex.lpszClassName = L"Example";
    ATOM at1 = RegisterClassEx(&wcex);
    assert(at1 != 0);
    // Register again, should fail with error 1410
    ATOM at2 = RegisterClassEx(&wcex);
    assert(at2 == 0);
    int err = GetLastError();
    assert(err == ERROR_CLASS_ALREADY_EXISTS);
    return 0;
}

查看您的代码,寻找 coclass 使用 RegisterClass(Ex) 的地方。当实例被销毁时,它必须使用 UnregisterClass。或者避免再次注册窗口类。或者忽略具体的错误代码。

关于c++ - CComPtr CoCreateInstance 返回 0x80070582(类已存在。),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2858979/

相关文章:

python - STL 的 gdb pretty-print 抛出 "TypeError"

c++ - 调用 `gdk_rgba_to_string()` 时出现段错误

c# - 将 COM 对象添加到托管代码

c++ - 如何在DLL内的成员函数中使用互斥锁/关键部分

memory-management - 使用 CoTaskMemAlloc 时,我应该始终调用 CoTaskMemFree 吗?

c++ - 为什么重启后串口读取不起作用?

c++ - 无效使用 void 表达式,怎么办?

c# - 在 office 2010 中将受密码保护的 OpenXml Word 文档重新保存为受密码保护的二进制 Word 时显示错误

c++ - 如何将 C++ COM 组件升级到云部署

c++ - 仅双击运行时 basic_string 析构函数上的 qt C++ 异常