gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:57:04 24 4
gpt4 key购买 nike

假设我有一个带有以下伪代码的 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 构造函数的文件句柄。这使您有机会在失败时捕获错误代码。

关于delphi - 为什么在 DLL 库中调用 GetLastError 时返回 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15438409/

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