ShLwApi.StrFormatByteSize和Delphi 2010 Unicode

时间:2009-11-30 00:17:29

标签: delphi unicode delphi-2010

有人可以帮我解决这个问题:

{$IFDEF UNICODE}
function FormatStringByteSize( TheSize: Cardinal ): string;
{ Return a cardinal as a string formated similar to the statusbar of Explorer }
var
  Buff: string;
  Count: Integer;
begin
  Count := Length(Buff);
  FillChar(Buff, Count, 0);
  ShLwApi.StrFormatByteSize( TheSize, PWideChar(Buff), Length( Buff ) * SizeOf( WideChar ) );
  Result := Buff;
end;
{$ENDIF}

2 个答案:

答案 0 :(得分:1)

您需要先设置buff的长度。 (长度buff = 0)

然后

  1. 将TheSize更改为Int64 - 尺寸>需要此尺寸反正4GB。
  2. 也许更改对StrFormatByteSizeW的调用(Delphi“标题”应该在D2009中完成此操作+)
  3. 尽管名称不同,但FillChar希望大小以字节为单位,而不是字符。但是这不会影响结果。
  4. function FormatStringByteSize( TheSize: int64 ): string;
    // Return an Int64 as a string formatted similar to the status bar of Explorer 
    var
      Buff: string;
    begin
      SetLength(Buff, 20);
      ShLwApi.StrFormatByteSizeW( TheSize, PWideChar(Buff), Length(Buff));
      Result := PChar(Buff);
    end;
    

    我现在无法在D2009 / 10中测试这个,因为还没有开始转向Unicode(下一个项目!)它在D2006中使用WideString。

答案 1 :(得分:0)

至少在Delphi 2009中(无法在2010版本中测试,因为我没有),StrFormatByteSize()函数是Ansi版本(StrFormatByteSizeA())的别名,而不是广泛的char版本(StrFormatByteSizeW())和大多数其他Windows API函数一样。因此,您应该直接使用宽字符版本 - 也适用于早期的Delphi版本,以便能够处理大于4 GB的文件(系统)。

不需要中间缓冲区,您可以利用StrFormatByteSizeW()将指向转换结果的指针作为PWideChar返回的事实:

{$IFDEF UNICODE}
function FormatStringByteSize(ASize: int64): string;
{ Return a cardinal as a string formatted similar to the status bar of Explorer }
const
  BufLen = 20;
begin
  SetLength(Result, BufLen);
  Result := StrFormatByteSizeW(ASize, PChar(Result), BufLen);
end;
{$ENDIF}