I tried to use writeunicodestring method with utf8decode, but it adds mess to the stream
Something appears to be very messed up with
TStringStream.WriteUnicodeString(). If the stream is empty, it doesn't write anything at all. And if the stream is not empty, it writes WAY too many bytes (4098 instead of 22).
Also, FYI using
BytesOf() won't work, because it will not return UCS2/UTF16-encoded bytes when passed a decoded
UnicodeString.
This works for me:
var
s: string;
us: UnicodeString;
out: TBytes;
strm: TBytesStream;
begin
s := 'Это строка';
strm := TBytesStream.create;
strm.WriteWord(Length(s)); // add some bytes before
// either:
us := UTF8Decode(s);
strm.WriteBuffer(PByte(us)^, Length(us)*2);
// or:
out := TEncoding.Unicode.GetBytes(UTF8Decode(s));
strm.WriteBuffer(PByte(out)^, Length(out));
//
strm.WriteByte($00); // and after string
print_stream(strm);
strm.free;