Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last error (WSAGetLastError)?

How do I call WSAGetLastError() from WinAPI so I get the valid text error?

like image 700
Ivan Prodanov Avatar asked Apr 19 '09 14:04

Ivan Prodanov


2 Answers

[DllImport("ws2_32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern Int32 WSAGetLastError();

Also, on pinvoke.net it's said:

You should never PInvoke to GetLastError. Call Marshal.GetLastWin32Error instead!

System.Runtime.InteropServices.Marshal.GetLastWin32Error()

like image 145
abatishchev Avatar answered Nov 05 '22 06:11

abatishchev


WSAGetLastError is just a wrapper for the Win32 GetLastError function.

If you're doing things with P/Invoke, you can use the SetLastError parameter to the DllImport attribute. It tells .NET that the imported function will call SetLastError(), and that the value should be collected.

If the imported function fails, you can get at the last error with Marshal.GetLastWin32Error(). Alternatively, you can just throw new Win32Exception(), which uses this value automatically.

If you're not doing things with P/Invoke, you're out of luck: there's no guarantee that the last error value will be preserved long enough to make it back through multiple layers of .NET code. In fact, I'll link to Adam Nathan: never define a PInvoke signature for GetLastError.

like image 7
Roger Lipscombe Avatar answered Nov 05 '22 05:11

Roger Lipscombe