hstring_reference.cc 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright 2019 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. #include "base/win/hstring_reference.h"
  5. #include <windows.h>
  6. #include <wchar.h>
  7. #include <winstring.h>
  8. #include "base/check_op.h"
  9. #include "base/numerics/safe_conversions.h"
  10. namespace base {
  11. namespace {
  12. bool g_winrt_string_loaded = false;
  13. decltype(&::WindowsCreateStringReference) GetWindowsCreateStringReference() {
  14. static auto const create_string_reference_func =
  15. []() -> decltype(&::WindowsCreateStringReference) {
  16. const HMODULE handle =
  17. ::LoadLibraryEx(L"combase.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32);
  18. if (handle) {
  19. return reinterpret_cast<decltype(&::WindowsCreateStringReference)>(
  20. ::GetProcAddress(handle, "WindowsCreateStringReference"));
  21. }
  22. return nullptr;
  23. }();
  24. return create_string_reference_func;
  25. }
  26. } // namespace
  27. namespace win {
  28. // static
  29. bool HStringReference::ResolveCoreWinRTStringDelayload() {
  30. g_winrt_string_loaded = GetWindowsCreateStringReference() != nullptr;
  31. return g_winrt_string_loaded;
  32. }
  33. HStringReference::HStringReference(const wchar_t* str, size_t length) {
  34. DCHECK(g_winrt_string_loaded);
  35. // String must be null terminated for WindowsCreateStringReference.
  36. // nullptr str is OK so long as the length is 0.
  37. DCHECK(str ? str[length] == L'\0' : length == 0);
  38. // If you nullptr crash here, you've failed to call
  39. // ResolveCoreWinRTStringDelayLoad and check its return value.
  40. const HRESULT hr = GetWindowsCreateStringReference()(
  41. str, checked_cast<UINT32>(length), &hstring_header_, &hstring_);
  42. // All failure modes of WindowsCreateStringReference are handled gracefully
  43. // but this class.
  44. DCHECK_EQ(hr, S_OK);
  45. }
  46. HStringReference::HStringReference(const wchar_t* str)
  47. : HStringReference(str, str ? wcslen(str) : 0) {}
  48. } // namespace win
  49. } // namespace base