scoped_hstring.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2017 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.
  4. #ifndef BASE_WIN_SCOPED_HSTRING_H_
  5. #define BASE_WIN_SCOPED_HSTRING_H_
  6. #include <hstring.h>
  7. #include "base/compiler_specific.h"
  8. #include "base/scoped_generic.h"
  9. #include "base/strings/string_piece_forward.h"
  10. namespace base {
  11. namespace internal {
  12. // Scoped HSTRING class to maintain lifetime of HSTRINGs allocated with
  13. // WindowsCreateString().
  14. struct BASE_EXPORT ScopedHStringTraits {
  15. static HSTRING InvalidValue() { return nullptr; }
  16. static void Free(HSTRING hstr);
  17. };
  18. } // namespace internal
  19. namespace win {
  20. // ScopedHString is a wrapper around an HSTRING. Note that it requires certain
  21. // functions that are only available on Windows 8 and later, and that these
  22. // functions need to be delayloaded to avoid breaking Chrome on Windows 7.
  23. //
  24. // Callers MUST check the return value of ResolveCoreWinRTStringDelayLoad()
  25. // *before* using ScopedHString.
  26. //
  27. // One-time Initialization for ScopedHString:
  28. //
  29. // bool success = ScopedHString::ResolveCoreWinRTStringDelayload();
  30. // if (success) {
  31. // // ScopeHString can be used.
  32. // } else {
  33. // // Handle error.
  34. // }
  35. //
  36. // Example use:
  37. //
  38. // ScopedHString string = ScopedHString::Create(L"abc");
  39. //
  40. // Also:
  41. //
  42. // HSTRING win_string;
  43. // HRESULT hr = WindowsCreateString(..., &win_string);
  44. // ScopedHString string(win_string);
  45. //
  46. class BASE_EXPORT ScopedHString
  47. : public ScopedGeneric<HSTRING, base::internal::ScopedHStringTraits> {
  48. public:
  49. // Constructs a ScopedHString from an HSTRING, and takes ownership of |hstr|.
  50. explicit ScopedHString(HSTRING hstr);
  51. static ScopedHString Create(WStringPiece str);
  52. static ScopedHString Create(StringPiece str);
  53. // Loads all required HSTRING functions, available from Win8 and onwards.
  54. static bool ResolveCoreWinRTStringDelayload() WARN_UNUSED_RESULT;
  55. // Returns a view into the memory buffer managed by the instance. The returned
  56. // StringPiece is only valid during the lifetime of this ScopedHString
  57. // instance.
  58. WStringPiece Get() const;
  59. // Returns a copy of the instance as a UTF-8 string.
  60. std::string GetAsUTF8() const;
  61. };
  62. } // namespace win
  63. } // namespace base
  64. #endif // BASE_WIN_SCOPED_HSTRING_H_