As the NativeMethods class should not be marked with SuppressUnmanagedCodeAttribute , P/Invokes placed within in it, will require UnmanagedCode permission. As most applications run from the local machine and run with FullTrust, this is usually not a problem. However, if you developing reusable libraries, you should instead consider defining a SafeNativeMethods or UnsafeNativeMethods class. For more information, see the appropriate content blocks below.
The following example shows a method Interaction.Beep that wraps the MessageBeep function from user32.dll, the MessageBeep p/invoke is placed within the NativeMethods class.
[C#]
using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
public static class Interaction
{
// Callers require Unmanaged permission
public static void Beep()
{
// No need to demand a permission as callers of Interaction.Beep
// will require UnmanagedCode permission
if (!NativeMethods.MessageBeep(-1))
throw new Win32Exception();
}
}
internal static class NativeMethods
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool MessageBeep(int uType);
}
[Visual Basic]
Imports System
Imports System.Runtime.InteropServices
Imports System.ComponentModel
Public NotInheritable Class Interaction
Private Sub New()
End Sub
' Callers require Unmanaged permission
Public Shared Sub Beep()
' No need to demand a permission as callers of Interaction.Beep
' will require UnmanagedCode permission
If Not NativeMethods.MessageBeep(-1) Then
Throw New Win32Exception()
End If
End Sub
End Class
Friend NotInheritable Class NativeMethods
Private Sub New()
End Sub
<DllImport("user32.dll", CharSet:=CharSet.Auto)> _
Friend Shared Function MessageBeep(ByVal uType As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function
End Class
In the example above, any assembly that calls NativeMethod.MessageBeep or Interaction.Beep will require UnmanagedCode permission.