How to: Request Permission to Access Unmanaged Code

You can easily request permissions by applying attributes that represent the permissions you want to request to the assembly level of your code. The attributes you use can vary, depending on the permissions you are requesting. Requests are compiled into the metadata of your application's assembly manifest and evaluated by the runtime when your code is loaded into memory during execution.

The following example shows how to request permission to access unmanaged code. Note that it uses a SecurityPermissionAttribute and it specifies two values: a SecurityAction value that specifies the kind of permission request being made (RequestMinimum, in this case), and a flag that indicates which permission is being requested. In this case, SecurityPermissionFlag.UnmanagedCode specifies a request for unmanaged code permission. The assembly: syntax tells the compiler that the attribute is being applied at the assembly level.

Example

Imports System
Imports System.Security.Permissions
Imports System.Runtime.InteropServices
'The request is placed at the assembly level.
<assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, Flags := SecurityPermissionFlag.UnmanagedCode)>

Namespace MyNamespace
   Public Class MyClass1
      Public Sub New()

      End Sub
       
      Public Sub MyMethod()
         'Perform interoperation with unmanaged code here.
      End Sub 
   End Class
End Namespace
//The request is placed at the assembly level.
using System.Security.Permissions;
[assembly:SecurityPermissionAttribute(SecurityAction.RequestMinimum, Flags = SecurityPermissionFlag.UnmanagedCode)]

namespace MyNamespace {
   using System;
   using System.Runtime.InteropServices;
   
   public class MyClass {
      public MyClass() {

      }
      public void MyMethod() {
        //Perform interoperation with unmanaged code here.
      }
   }
}

If the previous code does not receive SecurityPermission with the UnmanagedCode flag, the runtime throws a PolicyException and the code is not allowed to execute. However, if the code does receive that permission, then it is allowed to execute.

See Also

Concepts

Requesting Permissions

Reference

SecurityPermissionAttribute

SecurityAction

SecurityPermissionFlag.UnmanagedCode

Other Resources

Extending Metadata Using Attributes

Code Access Security

Metadata and Self-Describing Components