将文字转换为 PChar / PAnsiChar
Casting literals to PChar / PAnsiChar
我有一个非常愚蠢的问题...
为什么这个代码:
PChar('x');
导致"Access violation"错误?
编译器优化?
示例:
var s: String;
...
s := StrPas(PAnsiChar('x'));
这会导致 Delphi 5 / Delphi XE
中的 AV
或者这个:
Windows.MessageBox(0, PChar('x'), PChar('y'), 0);
这会在 Delphi 5 中导致 AV,但在 Delphi XE 中不会
XE 中有一个空的 MessageBox
控制台示例:
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils, Windows;
var s: String;
begin
s := StrPas(PChar('xxx')); // EAccessViolation here
end.
StrPas(PAnsiChar('x'));
我假设 'x'
被视为字符文字而不是字符串文字。因此演员阵容无效。如果是这样,那么这将按您预期的那样工作
StrPas('x');
由于隐式转换。或者
StrPas(PAnsiChar(AnsiString('x')));
感谢显式转换。
我认为前者可能是首选。文字不需要强制转换为空终止指针类型。编译器可以在没有转换的情况下发出正确的代码。并且总是 运行 有抑制错误的风险。
我有一个非常愚蠢的问题... 为什么这个代码:
PChar('x');
导致"Access violation"错误? 编译器优化?
示例:
var s: String;
...
s := StrPas(PAnsiChar('x'));
这会导致 Delphi 5 / Delphi XE
中的 AV或者这个:
Windows.MessageBox(0, PChar('x'), PChar('y'), 0);
这会在 Delphi 5 中导致 AV,但在 Delphi XE 中不会 XE 中有一个空的 MessageBox
控制台示例:
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils, Windows;
var s: String;
begin
s := StrPas(PChar('xxx')); // EAccessViolation here
end.
StrPas(PAnsiChar('x'));
我假设 'x'
被视为字符文字而不是字符串文字。因此演员阵容无效。如果是这样,那么这将按您预期的那样工作
StrPas('x');
由于隐式转换。或者
StrPas(PAnsiChar(AnsiString('x')));
感谢显式转换。
我认为前者可能是首选。文字不需要强制转换为空终止指针类型。编译器可以在没有转换的情况下发出正确的代码。并且总是 运行 有抑制错误的风险。