fork download
  1. version(Windows) import std.c.windows.windows;
  2. version(Windows) import std.windows.syserror;
  3. //version(Posix) import iconv;
  4. import std.utf;
  5. import std.string;
  6. import std.stdio;
  7.  
  8. extern(C) export
  9. {
  10. alias void* iconv_t;
  11.  
  12. size_t iconv(iconv_t cd,
  13. char **inbuf, size_t *inbytesleft,
  14. char **outbuf, size_t *outbytesleft);
  15. iconv_t iconv_open(const char *tocode, const char *fromcode);
  16. int iconv_close(iconv_t cd);
  17. }
  18.  
  19. version(Windows) string charcterEncodingConvert(const(char)[] str, uint fromCodePage, uint toCodePage)
  20. {
  21. int result;
  22. wchar[] wstr;
  23. char[] rstr;
  24.  
  25. result = MultiByteToWideChar(fromCodePage, 0, str.ptr, str.length, null, 0);
  26. wstr.length = result;
  27. result = MultiByteToWideChar(formCodePage, 0, str.ptr, str.length, wstr.ptr, wstr.length);
  28. if(result == 0) throw new Exception("Couldn't convert string: " ~ sysErrorString(GetLastError()));
  29.  
  30. result = WideCharToMultiByte(toCodePage, 0, wstr.ptr, wstr.length, null, 0, null, null);
  31. rstr.length = result;
  32. result = WideCharToMultiByte(toCodePage, 0, wstr.ptr, wstr.length, rstr.ptr, rstr.length, null, null);
  33. if(result == 0) throw new Exception("Couldn't convert string: " ~ sysErrorString(GetLastError()));
  34.  
  35. return cast(immutable)rstr;
  36. }
  37.  
  38. version(Posix) string charcterEncodingConvert(const(char)[] str, const(char)[] fromcode, const(char)[] tocode)
  39. {
  40. iconv_t cd = iconv_open(toStringz(tocode), toStringz(fromcode));
  41. if(cd is cast(iconv_t)-1) throw new Exception("Couldn't convert string");
  42. scope(exit) iconv_close(cd);
  43.  
  44. char[] cstr = str.dup;
  45. char[] rstr = new char[str.length * 2];
  46. char* inbuf = cstr.ptr;
  47. char* outbuf = rstr.ptr;
  48. size_t inleft = cstr.length;
  49. size_t outleft = rstr.length;
  50.  
  51. size_t result = iconv(cd, &inbuf, &inleft, &outbuf, &outleft);
  52. if(result == cast(size_t)-1) throw new Exception("Couldn't convert string");
  53.  
  54. rstr.length = rstr.length - outleft;
  55. return cast(immutable)rstr;
  56. }
  57.  
  58. int main(string[] argv)
  59. {
  60. string str = charcterEncodingConvert("こんにちは", "UTF-8", "SHIFT_JIS");
  61. writeln(str);
  62. return 0;
  63. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.o: In function `_D4prog23charcterEncodingConvertFAxaAxaAxaZAya':
prog.d:(.text._D4prog23charcterEncodingConvertFAxaAxaAxaZAya+0x23): undefined reference to `_imp__iconv_open'
prog.d:(.text._D4prog23charcterEncodingConvertFAxaAxaAxaZAya+0xb8): undefined reference to `_imp__iconv'
prog.d:(.text._D4prog23charcterEncodingConvertFAxaAxaAxaZAya+0x12c): undefined reference to `_imp__iconv_close'
collect2: ld returned 1 exit status
--- errorlevel 1
stdout
Standard output is empty