#include <iostream>
#include <thread>
#include <comdef.h>
#include <atlbase.h>
void InitializeMTA() {
HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
if (SUCCEEDED(hr)) {
std::cout << "MTA 初始化成功" << std::endl;
// 进行 COM 操作
CoUninitialize();
} else {
std::cerr << "MTA 初始化失败,错误代码: " << std::hex << hr << std::endl;
}
}
int main() {
// 确保主线程使用 STA
HRESULT hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
if (SUCCEEDED(hr)) {
std::cout << "STA 初始化成功" << std::endl;
// 创建新线程初始化 MTA
std::thread mtaThread(InitializeMTA);
mtaThread.join(); // 等待 MTA 线程完成
CoUninitialize(); // 清理 STA
} else {
std::cerr << "STA 初始化失败,错误代码: " << std::hex << hr << std::endl;
}
return 0;
}