1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef BASE_WIN_SCOPED_COM_INITIALIZER_H_
6 #define BASE_WIN_SCOPED_COM_INITIALIZER_H_
9 #include "base/basictypes.h"
10 #include "base/logging.h"
11 #include "build/build_config.h"
20 // Initializes COM in the constructor (STA or MTA), and uninitializes COM in the
22 class ScopedCOMInitializer
{
24 // Enum value provided to initialize the thread as an MTA instead of STA.
25 enum SelectMTA
{ kMTA
};
27 // Constructor for STA initialization.
28 ScopedCOMInitializer() {
29 Initialize(COINIT_APARTMENTTHREADED
);
32 // Constructor for MTA initialization.
33 explicit ScopedCOMInitializer(SelectMTA mta
) {
34 Initialize(COINIT_MULTITHREADED
);
37 ScopedCOMInitializer::~ScopedCOMInitializer() {
39 // Using the windows API directly to avoid dependency on platform_thread.
40 DCHECK_EQ(GetCurrentThreadId(), thread_id_
);
46 bool succeeded() const { return SUCCEEDED(hr_
); }
49 void Initialize(COINIT init
) {
51 thread_id_
= GetCurrentThreadId();
53 hr_
= CoInitializeEx(NULL
, init
);
58 // In debug builds we use this variable to catch a potential bug where a
59 // ScopedCOMInitializer instance is deleted on a different thread than it
60 // was initially created on. If that ever happens it can have bad
61 // consequences and the cause can be tricky to track down.
65 DISALLOW_COPY_AND_ASSIGN(ScopedCOMInitializer
);
76 // Do-nothing class for other platforms.
77 class ScopedCOMInitializer
{
79 enum SelectMTA
{ kMTA
};
80 ScopedCOMInitializer() {}
81 explicit ScopedCOMInitializer(SelectMTA mta
) {}
82 ~ScopedCOMInitializer() {}
84 bool succeeded() const { return true; }
87 DISALLOW_COPY_AND_ASSIGN(ScopedCOMInitializer
);
95 #endif // BASE_WIN_SCOPED_COM_INITIALIZER_H_