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返回的错误代码是一个线程局部变量,并在您的线程中运行的所有代码之间共享.因此,为了捕获错误代码,您需要在失败的函数返回后立即调用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 举报,一经查实,本站将立刻删除。