一个 UTF-8 字符转换单元 <br>提交日期:2004-5-28 作者?: itren <br> <br>关键词:UTF-8 <br>{$J+,Z4}<br>unit UTF8;<br>{$IFDEF CONDITIONALEXPRESSIONS} {$WARN SYMBOL_PLATFORM OFF} {$ENDIF}<br><br>{------------------------------------------------------------------------------}<br>{ }<br>{ UTF8 utilities - especially for versions prior to Delphi 6 }<br>{ }<br>{ This code is }<br>{ Copyright (C) 2003 by Michael in der Wiesche }<br>{ }<br>{------------------------------------------------------------------------------}<br><br> Secure memory management prevents passphrases from being swapped to disk<br>// Using secure memory within Delphi causes crashes, so it is disabled when debugging<br>// IsDebuggerPresent isn't available on Windows 95 - but neither is PGP 8.X - so we can use it ...<br><br>interface<br><br>type UTF8String = type String;<br><br>var AnsiToUtf8PChar: procedure(const Ansi, Utf8: PChar; var Len: Cardinal); stdcall;<br>var Utf8ToAnsiPChar: procedure(const Utf8, Ansi: PChar; var Len: Cardinal); stdcall;<br><br>function AnsiToUtf8(const S: String): UTF8String;<br>function Utf8ToAnsi(const S: UTF8String): String;<br>function Utf8OrAnsi(const S: UTF8String): String;<br><br>const MaxUTF8Length = 256*6;<br><br>implementation<br><br>uses Windows, SysUtils, pgpBase;<br><br>var SecureMemoryMgr: procedure; stdcall;<br>var DefaultMemoryMgr: procedure; stdcall;<br>var IsSecureMemoryMgr: function: Longbool; stdcall;<br><br>function AnsiToUtf8(const S: String): UTF8String;<br>var<br> Len: Cardinal;<br>begin<br> Len:=succ(Length(S) shl 2);<br> SetLength(Result, Len);<br> AnsiToUtf8PChar(PChar(S), PChar(Result), Len);<br> SetLength(Result, Len);<br>end;<br><br>function Utf8ToAnsi(const S: UTF8String): String;<br>var<br> Len: Cardinal;<br>begin<br> Len:=succ(Length(S));<br> SetLength(Result, Len);<br> Utf8ToAnsiPChar(PChar(S), PChar(Result), Len);<br> SetLength(Result, Len);<br>end;<br><br>function Utf8OrAnsi(const S: UTF8String): String;<br>begin<br> Result:=Utf8ToAnsi(S);<br> if Result='' then Result:=S;<br>end;<br><br>function Debugging: Longbool;<br>var<br> IsDebuggerPresent: function: Bool; stdcall;<br>begin<br> IsDebuggerPresent:=GetProcAddress(GetModuleHandle(Kernel32), 'IsDebuggerPresent');<br> Result:=IsDebuggerPresent;<br>end;<br><br>function UsingSecMemIsSafe: Longbool;<br>begin<br> Result:=(PGP8X and not Debugging and (pos('delphi32.exe', LowerCase(ParamStr(0)))=0));<br>end;<br><br>initialization<br> if hUTF8Lib<>0 then begin<br> AnsiToUtf8PChar:=GetProcAddress(hUTF8Lib, ptr(1));<br> Utf8ToAnsiPChar:=GetProcAddress(hUTF8Lib, ptr(2));<br> SecureMemoryMgr:=GetProcAddress(hUTF8Lib, ptr(3));<br> DefaultMemoryMgr:=GetProcAddress(hUTF8Lib, ptr(4));<br> IsSecureMemoryMgr:=GetProcAddress(hUTF8Lib, ptr(5));<br> if UsingSecMemIsSafe then SecureMemoryMgr;<br> end;<br><br>finalization<br> if (hUTF8Lib<>0) and IsSecureMemoryMgr then DefaultMemoryMgr;<br><br>end.