82 lines
1.9 KiB
Plaintext
82 lines
1.9 KiB
Plaintext
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.
|
|
|
|
|
|
== Noncompliant Code Example
|
|
|
|
[source,csharp]
|
|
----
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
== Compliant Solution
|
|
|
|
[source,csharp]
|
|
----
|
|
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[]
|