gpt4 book ai didi

delphi - 为什么在我的程序开始之前 GetLastError 出现错误?

转载 作者:行者123 更新时间:2023-12-03 15:37:45 25 4
gpt4 key购买 nike

在调用像 ExtractShortPathName 这样的 Windows API 函数包装器后使用 GetLastError 时,我注意到 GetLastError 返回一个非零错误代码,无论是否对 ExtractShortPathName 的调用成功或失败。事实上,在我的程序执行之前似乎存在“最后一个错误”,例如

program TestGetLastError;

{$APPTYPE CONSOLE}
{$R *.res}

uses
System.SysUtils;

var
ErrorCode: Integer;

begin
try
ErrorCode := GetLastError;
if ErrorCode <> 0 then
RaiseLastOSError;
except
on E: Exception do
WriteLn(E.ClassName, ': ', E.Message);
end;
end.

结果:

EOSError: System Error.  Code: 122.
The data area passed to a system call is too small

我是否误解了什么或做错了什么?

如果 Delphi 运行时执行的操作导致设置了 GetLastError,那么在程序开始执行之前清除该错误的正确方法是什么?我应该像 Delphi API 文档中的示例一样使用 SetLastError(ERROR_SUCCESS); 吗:

procedure TForm2.btRaiseLastClick(Sender: TObject);
begin
{ Set the last OS error to a bogus value. }
System.SetLastError(ERROR_ACCESS_DENIED);

try
RaiseLastOSError();
except
on Ex : EOSError do
MessageDlg('Caught an OS error with code: ' + IntToStr(Ex.ErrorCode), mtError, [mbOK], 0);
end;

{ Let the Delphi Exception dialog appear. }
RaiseLastOSError(ERROR_NOT_ENOUGH_MEMORY);

{ Finally set the last error to none. }
System.SetLastError(ERROR_SUCCESS);

if GetLastError() <> ERROR_SUCCESS then
MessageDlg('Whoops, something went wrong in the mean time!', mtError, [mbOK], 0);

{ No exception should be thrown here because last OS error is "ERROR_SUCCESS". }
CheckOSError(GetLastError());
end;

http://docwiki.embarcadero.com/CodeExamples/Tokyo/en/LastOSError_(Delphi)

最佳答案

GetLastError() 返回的值仅在 Windows API 调用失败后立即相关,并且该函数的文档指定通过调用 GetLastError( )

在该上下文之外调用它会返回先前调用的某些内容,这些内容可能来自您的代码、Delphi 运行时、您调用的 DLL,甚至是 Windows API 中的某些内容...

正如 GetLastError() 的 Windows API 文档所述:

You should call the GetLastError function immediately when a function's return value indicates that such a call will return useful data.

关于delphi - 为什么在我的程序开始之前 GetLastError 出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43244719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com