<span ><span >function</span><span > </span><span >MemoryStreamToString(M:</span><span > </span><span >TMemoryStream):</span><span > </span><span >String</span><span >;</span><span >var</span><span > </span><span >NewCapacity:</span><span > </span><span >Longint;</span><span >begin</span><span > </span><span >if</span><span > </span><span >(M.Size</span><span > </span><span >=</span><span > </span><span >0)</span><span > </span><span >or</span><span > </span><span >(M.Memory</span><span > </span><span >=</span><span > </span><span >nil</span><span >)</span><span > </span><span >then</span><span > </span><span >Result:=</span><span > </span><span >''</span><span > </span><span >else</span><span > </span><span >begin</span><span > </span><span >if</span><span > </span><span >TMemoryStreamProtected(M).Capacity</span><span > </span><span >=</span><span > </span><span >M.Size</span><span > </span><span >then</span><span > </span><span >begin</span><span > </span><span >NewCapacity:=</span><span > </span><span >M.Size+1;</span><span > </span><span >TMemoryStreamProtected(M).Realloc(NewCapacity);</span><span > </span><span >end</span><span >;</span><span > </span><span >NullString(M.Memory^)[M.Size]:=</span><span > </span><span >#0;</span><span > </span><span >Result:=</span><span > </span><span >StrPas(M.Memory);</span><span > </span><span >end</span><span >;</span><span >end</span><span >;</span></span>
我们如何转换这个代码以支持Unicode现在与Delphi 2009?
解决方法 你的代码是不必要的复杂,即使对于老版本的Delphi版本。为什么获取字符串版本的流强迫流的内存被重新分配?function MemoryStreamToString(M: TMemoryStream): string;begin SetString(Result,PChar(M.Memory),M.Size div SizeOf(Char));end;
它适用于所有的Delphi版本,而不仅仅是Delphi 2009。当流是空的没有任何特殊情况下工作。 SetString
是一个不起眼的功能。
如果您的流的内容没有更改为Unicode,切换到Delphi 2009,那么您应该使用此功能代替:
function MemoryStreamToString(M: TMemoryStream): AnsiString;begin SetString(Result,PAnsiChar(M.Memory),M.Size);end;
这相当于你的原始代码,但跳过特殊情况。
总结以上是内存溢出为你收集整理的在Delphi 2009中将TMemoryStream转换为’String’全部内容,希望文章能够帮你解决在Delphi 2009中将TMemoryStream转换为’String’所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)