用于shorttrings的Delphi编译器指令不起作用?

时间:2012-03-06 08:41:25

标签: string delphi delphi-xe2 compiler-directives

我正在尝试将项目从Delphi 4移植到Delphi XE2。我需要在项目中使用shortstring。根据Delphi帮助,$ H-应该使编译器使用string类型的短串。我已经使用了这个指令,但我没有看到任何区别。我写了一个小测试程序:

program Stringtest;

{$APPTYPE CONSOLE}

{$R *.res}
{$H- }
uses
  System.SysUtils;

var
 str : string;
 short : shortstring;
begin
  try
    str := 'testing';
    short := 'testing';
    Writeln('str ' +Format('%d', [sizeOf(str)]) );
    Writeln('short  ' +Format('%d', [sizeOf(short)])  );
    Readln; 
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

在我看来,strshort的输出应该相同,因为编译器应该将它们都视为shortstring。但str的大小为4,short的大小为256。有没有其他方法让编译器将string视为shortstring,或者是在源代码中用string替换shortstring的所有出现的唯一解决方案?

1 个答案:

答案 0 :(得分:7)

$ H-是遗留的,仅提供向后兼容性。没有办法强制Delphi XE2(或任何版本的Delphi编译器从D2009及更高版本)不使用Unicode作为默认字符串类型。

编译器指令仍然只是为了防止旧代码在编译时中断。当Delphi 2009以Unicode-only作为默认字符串类型发布时,有一点骚动,没有切换回恢复为AnsiString作为默认值。据解释,他们确定这几乎是不可能的,因为需要有两个不同版本的RTL,VCL等。允许ShortString成为默认值需要相同的东西。

您需要明确地将所有字符串引用更改为shortstring(或者更好,修复您的代码以不需要它们)。