Native methods are functions that reside in libraries outside the virtual machine. Being able to call them is useful for interoperability with applications and libraries written in other programming languages, in particular when performing platform-specific operations. However doing so comes with extra risks since it means stepping out of the security model of the virtual machine. It is therefore highly recommended to take extra steps, like input validation, when invoking native methods. This is best done by making the native method private and by providing a wrapper that performs these extra steps and verifications.

This rule raises an issue when a native method is declared public or its wrapper is too trivial.

Noncompliant Code Example

using System;
using System.Runtime.InteropServices;

namespace MyLibrary
{
  class Foo
  {
    [DllImport("mynativelib")]
    extern public static void Bar(string s, int x); // Noncompliant
  }
}

Compliant Solution

using System;
using System.Runtime.InteropServices;

namespace MyLibrary
{
  class Foo
  {
    [DllImport("mynativelib")]
    extern private static void Bar(string s, int x);

    public void BarWrapper(string s, int x)
    {
      if (s != null && x >= 0  && x < s.Length)
      {
        bar(s, x);
      }
    }
  }
}