mardi 16 juin 2015

Check at run time whether a P/Invoke function has the DllImportAttribute.SetLastError flag set

I would like to know if it's possible to determine in the next method, before calling the last win32 error code, whether the function to be invoked has an DllImportAttribute.SetLastError flag set.

Private Shared Sub SafePInvoke(Of T)(ByRef resultVar As T, ByVal [function] As Func(Of T))

resultVar = [function].Invoke

Dim lastError As Integer = Marshal.GetLastWin32Error

If lastError <> 0 Then
    Throw New Win32Exception([error]:=lastError, message:=String.Format("Function '{0}' thrown an unhandled Win32 exception with error code '{1}'.",
                                                                        [function].Method.ToString, CStr(lastError)))
End If

End Sub

Then for example if I have this definition:

<DllImport("user32.dll", SetLastError:=False)>
Friend Shared Function FunctionName() As Integer
End Function

And I do this:

Dim result As Integer
SafePInvoke(result, Function() FunctionName())

The SafePInvoke method should be able to determine whether the FunctionName has the SetLastError flag set to True or not.





Aucun commentaire:

Enregistrer un commentaire