rspec/rules/S4200/rule.adoc
2023-01-16 09:01:20 +01:00

51 lines
1.3 KiB
Plaintext

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
[source,csharp]
----
using System;
using System.Runtime.InteropServices;
namespace MyLibrary
{
class Foo
{
[DllImport("mynativelib")]
extern public static void Bar(string s, int x); // Noncompliant
}
}
----
== Compliant Solution
[source,csharp]
----
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);
}
}
}
}
----