All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S4200.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

Native methods are functions that reside in libraries outside the .NET runtime. Calling them is helpful for interoperability with applications and libraries written in other programming languages, mainly when performing platform-specific operations. However, doing so comes with additional risks since it means stepping out of the memory-safety model of the runtime. It is therefore highly recommended to take extra steps, like input validation, when invoking native methods. Making the native method private and providing a wrapper that performs these additional steps is the best way to do so.

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);
      }
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy