wstring_encode.cxx 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. * PANDA 3D SOFTWARE
  3. * Copyright (c) Carnegie Mellon University. All rights reserved.
  4. *
  5. * All use of this software is subject to the terms of the revised BSD
  6. * license. You should have received a copy of this license along
  7. * with this source code in a file named "LICENSE."
  8. *
  9. * @file wstring_encode.cxx
  10. * @author drose
  11. * @date 2011-08-29
  12. */
  13. #include "wstring_encode.h"
  14. #include <ctype.h>
  15. #include <sstream>
  16. #include <iomanip>
  17. #ifdef _WIN32
  18. #include <windows.h>
  19. #endif // _WIN32
  20. #ifdef _WIN32
  21. /**
  22. * Encodes std::wstring to std::string using UTF-8.
  23. */
  24. bool
  25. wstring_to_string(string &result, const wstring &source) {
  26. bool success = false;
  27. int size = WideCharToMultiByte(CP_UTF8, 0, source.data(), source.length(),
  28. nullptr, 0, nullptr, nullptr);
  29. if (size > 0) {
  30. char *buffer = new char[size];
  31. int rc = WideCharToMultiByte(CP_UTF8, 0, source.data(), source.length(),
  32. buffer, size, nullptr, nullptr);
  33. if (rc != 0) {
  34. result.assign(buffer, size);
  35. success = true;
  36. }
  37. delete[] buffer;
  38. }
  39. return success;
  40. }
  41. #endif // _WIN32
  42. #ifdef _WIN32
  43. /**
  44. * Decodes std::string to std::wstring using UTF-8.
  45. */
  46. bool
  47. string_to_wstring(wstring &result, const string &source) {
  48. bool success = false;
  49. int size = MultiByteToWideChar(CP_UTF8, 0, source.data(), source.length(),
  50. nullptr, 0);
  51. if (size > 0) {
  52. wchar_t *buffer = new wchar_t[size];
  53. int rc = MultiByteToWideChar(CP_UTF8, 0, source.data(), source.length(),
  54. buffer, size);
  55. if (rc != 0) {
  56. result.assign(buffer, size);
  57. success = true;
  58. }
  59. delete[] buffer;
  60. }
  61. return success;
  62. }
  63. #endif // _WIN32