rspec/rules/S4071/csharp/rule.adoc

82 lines
1.9 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
An incorrectly defined platform invoke method (marked with ``++System.Runtime.InteropServices.DllImportAttribute++``) can lead to runtime exceptions because of issues such as a misnamed function, faulty mapping of parameter and return value data types, and incorrect field specifications. If available, it is a lot less error prone, not to mention more secure and quite simpler, to call the equivalent managed method.
This rule raises an issue when a platform invoke method is called and a method with the equivalent functionality exists in the .Net framework library.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,csharp]
2021-04-28 16:49:39 +02:00
----
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace MyLibrary
{
public class Foo
{
public Foo() {}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern int ExpandEnvironmentStrings(
string lpSrc, StringBuilder lpDst, int nSize);
public void Bar()
{
string environmentVariable = "%TEMP%";
StringBuilder expandedVariable = new StringBuilder(100);
ExpandEnvironmentStrings( // Noncompliant
environmentVariable,
expandedVariable,
expandedVariable.Capacity);
}
}
}
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,csharp]
2021-04-28 16:49:39 +02:00
----
using System;
using System.Text;
namespace MyLibrary
{
public class Foo
{
public Foo() {}
public void Bar()
{
string environmentVariable = "%TEMP%";
StringBuilder expandedVariable = new StringBuilder(100);
Environment.ExpandEnvironmentVariables(environmentVariable);
}
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
include::highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]