【问题标题】:ShLwApi.StrFormatByteSize and Delphi 2010 UnicodeShLwApi.StrFormatByteSize 和 Delphi 2010 Unicode
【发布时间】:2009-11-30 00:17:28
【问题描述】:

谁能帮我解决这个问题:

{$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}

【问题讨论】:

  • 修复它?是什么让认为它有问题?你有没有做任何事情来尝试调试它?你明白它应该如何工作吗?您是否阅读过您正在调用的函数的文档?无论如何,您是从哪个网站复制此代码的?

标签: delphi unicode delphi-2010


【解决方案1】:

至少在 Delphi 2009 中(无法在 2010 版中测试,因为我没有它)StrFormatByteSize() 函数是 Ansi 版本 (StrFormatByteSizeA()) 的别名,而不是宽字符版本 (@ 987654324@),因为它适用于大多数其他 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}

【讨论】:

  • 这是标题翻译中的一个错误。朴素的 API 应该指向“W”版本。实际上是用PChar 声明的,在D2009 和D2010 中和PWideChar 是一样的。所以即使你调用它也是错误的。
  • 谢谢你,mghie...它现在完美地返回了一个字符串。谢谢艾伦。我没有注意到标题错误。是否已将 StrFormatByteSize 标记为在更新中修复?
【解决方案2】:

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

然后

  1. 将 TheSize 更改为 Int64 - 对于大于 4GB 的大小,您仍然需要这个。
  2. 也许改变对 StrFormatByteSizeW 的调用(Delphi“标题”应该在 D2009+ 中完成此操作)
  3. 尽管有名称,FillChar 期望大小以字节为单位,而不是字符。不过这不会影响结果。
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。

【讨论】:

  • 无论如何,对 FillChar 的调用并不是很有用。通过根本不调用它来避免错误调用它的风险(就像比尔所做的那样)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-09
  • 2012-04-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多