Kazz
Kazz

Reputation: 1180

How to "WINAPI::GetLastError" in QT application?

Why is last error in QT application always zero ?

SetLastError(23);
qDebug() << "LastError: " << GetLastError();

expected output: LastError: 23

actual output: LastError: 0

I can't google anything about this issue. Are these functions hooked by QT ?

Upvotes: 0

Views: 553

Answers (2)

David Heffernan
David Heffernan

Reputation: 613013

When you make calls to the runtime library then that in turn can call Win32 API functions, and reset the error value. Fix your code like this:

SetLastError(23);
DWORD err = GetLastError();
qDebug() << "LastError: " << err;

This ensures that you read the error value before the runtime makes calls to Win32 functions.

Upvotes: 3

Igor Tandetnik
Igor Tandetnik

Reputation: 52471

DWORD lastError = GetLastError();
qDebug() << "LastError: " << lastError;

Always grab the last error immediately after the API call that failed. Those intervening qDebug() and operator<< calls themselves call Windows API functions, which may or may not reset the last error.

Upvotes: 5

Related Questions