LibreOffice Module o3tl (master) 1
safeCoInitUninit.hxx
Go to the documentation of this file.
1/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
2/*
3 * This file is part of the LibreOffice project.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 */
9
10#pragma once
11
12#if defined _WIN32
13#include <prewin.h>
14
15// for CoInitializeEx / CoUninitialize
16#include <combaseapi.h>
17
18#include <postwin.h>
19
20// for std::abort
21#include <cstdlib>
22
23namespace o3tl
24{
25// Helpers for safe calls to CoInitializeEx and CoUninitialize in MSVC
26// Indeed if a thread has been already initialized with a concurrency model
27// (in LO case COINIT_APARTMENTTHREADED or COINIT_MULTITHREADED)
28// CoInitializeEx can't succeed without calling first CoUninitialize
29// also, CoUninitialize must be called the number of times CoInitializeEx has been called
30inline HRESULT safeCoInitializeEx(DWORD dwCoInit, int& nbReinit)
31{
32 HRESULT hr;
33 while ((hr = CoInitializeEx(nullptr, dwCoInit)) == RPC_E_CHANGED_MODE)
34 {
35 // so we're in RPC_E_CHANGED_MODE case
36 // the pb was it was already initialized with a different concurrency model
37 // close this init
38 CoUninitialize();
39 // and increment counter for dtr part
40 ++nbReinit;
41
42 // and keep on the loop if there were multi initializations
43 }
44 if (FAILED(hr))
45 std::abort();
46 return hr;
47}
48
49inline void safeCoUninitializeReinit(DWORD dwCoInit, int nbReinit)
50{
51 CoUninitialize();
52 // Put back all the inits, if there were, before the use of the caller to safeCoInitializeEx
53 for (int i = 0; i < nbReinit; ++i)
54 CoInitializeEx(nullptr, dwCoInit);
55}
56}
57#endif
58/* vim:set shiftwidth=4 softtabstop=4 expandtab cinoptions=b1,g0,N-s cinkeys+=0=break: */
int i
return hr