xmliconv_windows.pas 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. {
  2. This file is part of the Free Component Library
  3. libiconv-based XML decoder (Windows version).
  4. Binds to the native (not Cygwin or Mingw) build of libiconv.
  5. Copyright (c) 2009 by Sergei Gorelkin, [email protected]
  6. See the file COPYING.FPC, included in this distribution,
  7. for details about the copyright.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. **********************************************************************}
  12. unit xmliconv_windows;
  13. interface
  14. implementation
  15. uses
  16. xmlread;
  17. type
  18. iconv_t = Pointer;
  19. const
  20. iconvlib = 'iconv.dll';
  21. function iconv_open(ToCode, FromCode: PChar): iconv_t; cdecl; external iconvlib name 'libiconv_open';
  22. function iconv(__cd: iconv_t; __inbuf: PPChar; var __inbytesleft: size_t; __outbuf:ppchar; var __outbytesleft: size_t): size_t; cdecl; external iconvlib name 'libiconv';
  23. function iconv_close(cd: iconv_t): Integer; cdecl; external iconvlib name 'libiconv_close';
  24. function errno_location: PInteger; cdecl; external 'msvcrt.dll' name '_errno';
  25. function Iconv_Decode(Context: Pointer; InBuf: PChar; var InCnt: Cardinal; OutBuf: PWideChar; var OutCnt: Cardinal): Integer; stdcall;
  26. var
  27. OutChars: size_t;
  28. InChars : size_t;
  29. begin
  30. OutChars := OutCnt * sizeof(WideChar);
  31. InChars:=InCnt;
  32. Result := iconv(Context, @InBuf, InChars, @OutBuf, OutChars);
  33. InCnt:=InChars;
  34. OutCnt := OutChars div sizeof(WideChar);
  35. if Result = -1 then
  36. begin
  37. case errno_location^ of
  38. // when iconv reports insufficient input or output space, still return
  39. // a positive number of converted chars
  40. 7, 22: Result := OutCnt - (OutChars div sizeof(WideChar));
  41. else
  42. Result := -errno_location^;
  43. end;
  44. end;
  45. end;
  46. procedure Iconv_Cleanup(Context: Pointer); stdcall;
  47. begin
  48. iconv_close(Context);
  49. end;
  50. function GetIconvDecoder(const AEncoding: string; out Decoder: TDecoder): Boolean; stdcall;
  51. var
  52. f: iconv_t;
  53. begin
  54. f := iconv_open('UCS-2-INTERNAL', PChar(AEncoding));
  55. if f <> Pointer(-1) then
  56. begin
  57. Decoder.Context := f;
  58. Decoder.Decode := @Iconv_Decode;
  59. Decoder.Cleanup := @Iconv_Cleanup;
  60. Result := True;
  61. end
  62. else
  63. Result := False;
  64. end;
  65. initialization
  66. RegisterDecoder(@GetIconvDecoder);
  67. end.