文章来源:http://blog.csdn.net/yjswjm119/archive/2006/02/18/601807.aspx
// 功能:将 WideString 转换成 String
function ChWideToAnsi(const StrW: WideString): AnsiString;
var
nLen: integer;
begin
Result := StrW;
if Result <> '' then
begin
nLen := WideCharToMultiByte(936, 624, @StrW[1], -1, nil, 0, nil, nil);
SetLength(Result, nLen - 1);
if nLen > 1 then
WideCharToMultiByte(936, 624, @StrW[1], -1, @Result[1], nLen - 1, nil, nil);
end;
end;
// 功能:将 String 转换成 WideString
function ChAnsiToWide(const StrA: AnsiString): WideString;
var
nLen: integer;
begin
Result := StrA;
if Result <> '' then
begin
nLen := MultiByteToWideChar(936, 1, PChar(@StrA[1]), -1, nil, 0);
SetLength(Result, nLen - 1);
if nLen > 1 then
MultiByteToWideChar(936, 1, PChar(@StrA[1]), -1, PWideChar(@Result[1]), nLen - 1);
end;
end;
function UTF8ToWideString(const Stream: TStream): WideString;
var
nLen: Cardinal;
begin
try
SetLength(Result, Stream.Size div SizeOf(WideChar) * 3);
nLen := Utf8ToUnicode(@Result[1], Length(Result),
Pointer(DWord(TMemoryStream(Stream).Memory) + Stream.Position),
Stream.Size - Stream.Position);
SetLength(Result, nLen);
except
SetLength(Result, 0);
end;
end;
以上的方法,个人认为主要问题是不同类型的字符串,其长度不同。只要设置对在各种类型下字符串的长度正确就行了。