Domanda

I created the following code:

Function AnsiStringToStream(Const AString: AnsiString): TStream;
Begin
  Result := TStringStream.Create(AString, TEncoding.ANSI);
End;

But I'm "W1057 Implicit string cast from 'AnsiString' to 'string'"

There is something wrong with him?

Thank you.

È stato utile?

Soluzione

In D2009+, TStringStream expects a UnicodeString, not an AnsiString. If you just want to write the contents of the AnsiString as-is without having to convert the data to Unicode and then back to Ansi, use TMemoryStream instead:

function AnsiStringToStream(const AString: AnsiString): TStream; 
begin 
  Result := TMemoryStream.Create;
  Result.Write(PAnsiChar(AString)^, Length(AString));
  Result.Position := 0; 
end; 

Since AnsiString is codepage-aware in D2009+, ANY string that is passed to your function will be forced to the OS default Ansi encoding. If you want to be able to pass any 8-bit string type, such as UTF8String, without converting the data at all, use RawByteString instead of AnsiString:

function AnsiStringToStream(const AString: RawByteString): TStream; 
begin 
  Result := TMemoryStream.Create;
  Result.Write(PAnsiChar(AString)^, Length(AString));
  Result.Position := 0; 
end; 

Altri suggerimenti

The TStringStream constructor expects a string as its parameter. When you give it an an AnsiString instead, the compiler has to insert conversion code, and the fact that you've specified the TEncoding.ANSI doesn't change that.

Try it like this instead:

Function AnsiStringToStream(Const AString: AnsiString): TStream;
Begin
  Result := TStringStream.Create(string(AString));
End;

This uses an explicit conversion, and leaves the encoding-related work up to the compiler, which already knows how to take care of it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top