Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AnsiString To Stream

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.

like image 700
Jhonjhon_123 Avatar asked Dec 21 '22 22:12

Jhonjhon_123


2 Answers

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.

like image 174
Mason Wheeler Avatar answered Jan 04 '23 22:01

Mason Wheeler


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; 
like image 36
Remy Lebeau Avatar answered Jan 05 '23 00:01

Remy Lebeau