加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 为什么GetLastError在DLL库中调用时返回0?

发布时间:2020-12-15 04:22:58 所属栏目:大数据 来源:网络整理
导读:假设我有一个带有这个伪代码的DLL库: var LastError: DWORD;procedure DoSomethingWrong; stdcall;var FileStream: TFileStream;begin try FileStream := TFileStream.Create('?',fmCreate); except on EFCreateError do LastError := GetLastError; // - w
假设我有一个带有这个伪代码的DLL库:
var
  LastError: DWORD;

procedure DoSomethingWrong; stdcall;
var
  FileStream: TFileStream;
begin
  try
    FileStream := TFileStream.Create('?',fmCreate);
  except
    on EFCreateError do
      LastError := GetLastError; // <- why does GetLastError return 0 here ?
  end;
end;

为什么GetLastError函数在如上所示的DLL库中使用时返回0?有没有办法获得此案例的最后一个错误代码?

解决方法

您对GetLastError的调用返回0,因为在CreateFile返回后调用了其他API,并且您的异常代码将执行.

GetLastError返回的错误代码是一个线程局部变量,并在您的线程中运行的所有代码之间共享.因此,为了捕获错误代码,您需要在失败的函数返回后立即调用GetLastError.

documentation解释如下:

Functions executed by the calling thread set this value by calling the
SetLastError function. You should call the GetLastError function
immediately when a function’s return value indicates that such a call
will return useful data. That is because some functions call
SetLastError with a zero when they succeed,wiping out the error code
set by the most recently failed function.

如果您正在使用TFileStream.Create,那么框架不会让您有机会在适当的时候调用GetLastError.如果你真的想获得这些信息,你必须自己调用CreateFile并使用THandleStream而不是TFileStream.

这个想法是THandleStream你负责合成传递给THandleStream构造函数的文件句柄.这使您有机会在发生故障时捕获错误代码.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读