How do I call WSAGetLastError()
from WinAPI so I get the valid text error?
[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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With