Вызовы API Windows Mobile — успех, но GetLastWin32Error возвращает код ошибки. Стоит ли мне беспокоиться?
-
03-07-2019 - |
Вопрос
Я новичок в вызовах PInvoke.Я погуглил это, так как вопрос кажется достаточно простым, но без радости.
Я делаю несколько вызовов Windows Mobile API подряд (чтобы определить, запущено ли мое приложение, и затем повторно активировать его).Все работает отлично и отлично, но я хотел включить журналирование и т. д. на случай, если оно не работает нормально.
При написании этого кода я обнаружил, что буду получать коды ошибок, даже если мои вызовы, очевидно, возвращают действительный результат, и действительный результат успешно используется при последующем вызове (я думаю, это доказывает его правильность).
Например.Я вызываю CreateToolhelp32Snapshot, который возвращает мне дескриптор снимка запущенных в данный момент процессов.Вызов Marshal.GetLatWin32Error сразу после возврата возвращает ошибку 6, что, по-видимому, означает неверный дескриптор.Но возвращаемое значение успешно используется при последующих вызовах других методов, и весь процесс работает.Определенно именно этот конкретный вызов устанавливает ошибку 6, потому что если вы вызываете Marshal.GetLatWin32Error непосредственно перед вызовом, он возвращает 0.
Вызовы Process32First и Process32Next демонстрируют схожее поведение, т.е.они с радостью предоставляют мне информацию о процессе, но иногда выдают ошибку 6.Я (думаю) знаю, что это происходит, потому что я вызываю Marshal.GetLatWin32Error сразу до и после каждого вызова, а иногда до и 6 после каждого вызова.В настоящее время я всегда получаю успешный результат (либо дескриптор, который работает с последующими вызовами, либо значение, которое приводит к 1, если int, или true, если bool и информация о процессе успешно скопированы в мой буфер).
Итак... должно ли меня это волновать?Всё работает....Меня волнует, какая ошибка будет установлена, если я получу результат, который успешно используется остальной частью процесса?Моя интуиция подсказывает: да, правда?В любом случае, как мне на самом деле узнать, все ли в порядке, если я, очевидно, получаю успешный результат, но также установлен код ошибки?Мне снятся кошмары о выпуске нестабильной системы, которая не будет возвращать мне полезную информацию об ошибках.......
ОБНОВЛЯТЬ
Это результаты моего кода loggong, чтобы попытаться проиллюстрировать то, о чем я говорю, для всех, кто заинтересован.Короче говоря, код проверяет наличие уже запущенных копий самого себя, затем уже запущенных копий клиента, а затем повторно активирует клиент, если он был найден.
Method name: CreateToolhelp32Snapshot, Result: 605618176, Pre-call error code: 0, Post-call error code: 6
Method name: Process32First, Result: True, Pre-call error code: 6, Post-call error code: 6
Method name: Process32Next, Result: True, Pre-call error code: 6, Post-call error code: 6
Method name: Process32Next, Result: True, Pre-call error code: 6, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: False, Pre-call error code: 0, Post-call error code: 18
Method name: CloseToolhelp32Snapshot, Result: True, Pre-call error code: 18, Post-call error code: 6
Method name: CreateToolhelp32Snapshot, Result: 605618176, Pre-call error code: 6, Post-call error code: 0
Method name: Process32First, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: True, Pre-call error code: 0, Post-call error code: 0
Method name: Process32Next, Result: False, Pre-call error code: 0, Post-call error code: 18
Method name: CloseToolhelp32Snapshot, Result: True, Pre-call error code: 18, Post-call error code: 0
Method name: ShowWindow, Result: True, Pre-call error code: 0, Post-call error code: 120
Method name: SetForegroundWindow, Result: True, Pre-call error code: 120, Post-call error code: 6
Результаты всегда истинны, за исключением последних вызовов Process32Next, для которых ошибка с кодом 18 указывает на то, что была достигнута последняя запись.И я только что заметил, что ShowWindow приводит к ошибке 120, которая не поддерживается, поэтому я отвечу на этот вопрос.
Итак, мои два актуальных вопроса:
Почему ошибки, когда я добился успеха?
И если ошибки до и после вызова одинаковы, как мне узнать, была ли это старая ошибка или второе появление той же ошибки?
Решение
Не следует вызывать GetLastWin32Error (GetLastError), если CreateToolhelp32Snapshot не возвращает INVALID_HANDLE_VALUE.
Видеть http://msdn.microsoft.com/en-us/library/ms682489(VS.85).aspx
Другие советы
Вы ожидаете, что GetLastError() вернет 0 после каждого успешного вызова любой функции.Но это означает, что эти функции вызывают SetLastError(0) в своем эпилоге, что не всегда делается.Вот почему вы не можете отличить старый код ошибки от нового.Вызывайте GetLastError() только в тех случаях, когда MSDN рекомендует вам это сделать.