在 Delphi 2009 中将 TMemoryStream 转换为“字符串" [英] Converting TMemoryStream to 'String' in Delphi 2009

查看:29
本文介绍了在 Delphi 2009 中将 TMemoryStream 转换为“字符串"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Delphi 2009 之前,我们有以下代码:

We had the following code prior to Delphi 2009:

function MemoryStreamToString(M : TMemoryStream): String;
var
    NewCapacity: Longint;
begin
    if (M.Size = > 0) or (M.Memory = nil) then
       Result:= '' 
    else
    begin
       if TMemoryStreamProtected(M).Capacity = M.Size then
       begin
           NewCapacity:= M.Size+1;
           TMemoryStreamProtected(M).Realloc(NewCapacity);
       end;
       NullString(M.Memory^)[M.Size]:= #0;
       Result:= StrPas(M.Memory);
    end;
end;

我们现在如何使用 Delphi 2009 转换此代码以支持 Unicode?

How might we convert this code to support Unicode now with Delphi 2009?

推荐答案

您拥有的代码过于复杂,即使对于较旧的 Delphi 版本也是如此.毕竟,为什么要获取流的字符串版本会强制重新分配流的内存?

The code you have is unnecessarily complex, even for older Delphi versions. Why should fetching the string version of a stream force the stream's memory to be reallocated, after all?

function MemoryStreamToString(M: TMemoryStream): string;
begin
  SetString(Result, PChar(M.Memory), M.Size div SizeOf(Char));
end;

这适用于所有 Delphi 版本,而不仅仅是 Delphi 2009.它适用于流为空且没有任何特殊情况的情况.SetString 是一个被低估的函数.

That works in all Delphi versions, not just Delphi 2009. It works when the stream is empty without any special case. SetString is an under-appreciated function.

如果您切换到 Delphi 2009 后流的内容没有更改为 Unicode,那么您应该改用此函数:

If the contents of your stream aren't changing to Unicode with your switch to Delphi 2009, then you should use this function instead:

function MemoryStreamToString(M: TMemoryStream): AnsiString;
begin
  SetString(Result, PAnsiChar(M.Memory), M.Size);
end;

这等价于您的原始代码,但跳过了特殊情况.

That's equivalent to your original code, but skips the special cases.

这篇关于在 Delphi 2009 中将 TMemoryStream 转换为“字符串"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆