使用Delphi的数据类型错位?

mag*_*nus 1 memory delphi logging

添加以下Delphi函数后,我收到有关数据类型错位的错误: Project ... faulted with message: 'datatype misalignment at 0x77a7d7d8'. Process Stopped. Use Step or Run to continue.

我添加的功能如下.请注意,虽然只有时间戳实际写入文件,但该函数实际上已成功完成.

procedure Log(msg : String);
var
  tempFolderChars : array [0..MAX_PATH] of Char;
  tempFolder : string;
  logFile : TextFile;
  dt : TDateTime;
begin
  GetTempPath(SizeOf(tempFolderChars), tempFolderChars);
  tempFolder := IncludeTrailingPathDelimiter(String(tempFolderChars));
  dt := Now();

  AssignFile(logFile, tempFolder + 'GenericHolding.txt');
  if FileExists(tempFolder + 'GenericHolding.txt') then
    Append(logFile)
  else
    ReWrite(logFile);

  Write(logFile, FormatDateTime('yyyy-mm-dd hh:nn:ss ', now));
  Write(logFile, msg);
  Write(logFile, #13, #10);
  CloseFile(logFile);
end;
Run Code Online (Sandbox Code Playgroud)

编辑:添加了更多的组装输出.

ntdll.NtQueryInformationProcess:
77BAFAC8 B816000000       mov eax,$00000016
77BAFACD 33C9             xor ecx,ecx
77BAFACF 8D542404         lea edx,[esp+$04]
77BAFAD3 64FF15C0000000   call dword ptr fs:[$000000c0]
77BAFADA 83C404           add esp,$04
77BAFADD C21400           ret $0014
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 5

CharAnsiChar(SizeOf(Char)=1)在2007年德尔福和更早的版本,但是是WideChar(SizeOf(Char)=2)在2009年和以后德尔福.

GetTempPath()期望第一个参数指定缓冲区可以容纳的字符数,但是您要指定字节数.

在Delphi 2007和更早版本中,SizeOf(tempFolderChars)并且Length(tempFolderChars)会有相同的价值,但在Delphi 2009及更高版本中它们将不会相同.在后一种情况下,你告诉GetTempPath()你可以接受两倍于你真实的角色.

你需要SizeOf(tempFolderChars)改为Length(tempFolderChars).您还需要注意返回值GetTempPath(),因为它告诉您实际写入缓冲区的字符数.

试试这个:

procedure Log(msg : String);
var
  tempFolderChars : array [0..MAX_PATH] of Char;
  tempFolder : string;
  len: DWORD;
  ...
begin
  len := GetTempPath(Length(tempFolderChars), tempFolderChars);
  if len = 0 then Exit;
  SetString(tempFolder, tempFolderChars, len);
  tempFolder := IncludeTrailingPathDelimiter(tempFolder);
  ...
end;
Run Code Online (Sandbox Code Playgroud)