SDL_windows.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2013 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_config.h"
  19. #if defined(__WIN32__) || defined(__WINRT__)
  20. #include "SDL_error.h"
  21. #include "SDL_windows.h"
  22. #include "SDL_assert.h"
  23. #include <objbase.h> /* for CoInitialize/CoUninitialize (Win32 only) */
  24. /* Sets an error message based on GetLastError() */
  25. int
  26. WIN_SetErrorFromHRESULT(const char *prefix, HRESULT hr)
  27. {
  28. TCHAR buffer[1024];
  29. char *message;
  30. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, hr, 0,
  31. buffer, SDL_arraysize(buffer), NULL);
  32. message = WIN_StringToUTF8(buffer);
  33. SDL_SetError("%s%s%s", prefix ? prefix : "", prefix ? ": " : "", message);
  34. SDL_free(message);
  35. return -1;
  36. }
  37. /* Sets an error message based on GetLastError() */
  38. int
  39. WIN_SetError(const char *prefix)
  40. {
  41. return WIN_SetErrorFromHRESULT(prefix, GetLastError());
  42. }
  43. HRESULT
  44. WIN_CoInitialize(void)
  45. {
  46. #ifdef __WINRT__
  47. /* DLudwig: On WinRT, it is assumed that COM was initialized in main().
  48. CoInitializeEx is available (not CoInitialize though), however
  49. on WinRT, main() is typically declared with the [MTAThread]
  50. attribute, which, AFAIK, should initialize COM.
  51. */
  52. return S_OK;
  53. #else
  54. const HRESULT hr = CoInitialize(NULL);
  55. /* S_FALSE means success, but someone else already initialized. */
  56. /* You still need to call CoUninitialize in this case! */
  57. if (hr == S_FALSE) {
  58. return S_OK;
  59. }
  60. return hr;
  61. #endif
  62. }
  63. void
  64. WIN_CoUninitialize(void)
  65. {
  66. #ifndef __WINRT__
  67. CoUninitialize();
  68. #endif
  69. }
  70. #endif /* __WIN32__ */
  71. /* vi: set ts=4 sw=4 expandtab: */