微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

假设我有一个带有这个伪代码的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构造函数文件句柄.这使您有机会在发生故障时捕获错误代码.

原文地址:https://www.jb51.cc/delphi/101668.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐