P/Invokes should be static and not be publicly visible
Methods marked DllImportAttribute (or VB Declare) access unmanaged code via Platform Invocation Services. Keep them private or internal so your library can't be used to breach security by giving callers access to unmanaged APIs. Matches DllImportAttribute methods declared public or non-static.
How to fix
Change the method's access level and/or declare it static.
CQLinq source
This rule is written in CQLinq, C# LINQ over the NDepend code model. It ships with every new NDepend project: you can read it, adapt it, or use it as a starting point for your own custom rules.
// <Name>P/Invokes should be static and not be publicly visible</Name>
// <Id>ND2400:PInvokesShouldBeStaticAndNotBePubliclyVisible</Id>
warnif count > 0 from m in Application.Methods where
!m.IsThirdParty &&
(m.HasAttribute ("System.Runtime.InteropServices.DllImportAttribute".AllowNoMatch())) &&
( m.IsPubliclyVisible ||
!m.IsStatic)
select new {
m,
m.Visibility,
m.IsStatic,
Debt = 5.ToMinutes().ToDebt(),
Severity = Severity.High
}
//<Expl>
// The *P/Invoke {0}* should be declared as *static*
// and should not be made *public*.
//</Expl>
//<Desc>
// Methods marked **DllImportAttribute** (or VB **Declare**) access
// unmanaged code via **Platform Invocation Services**. Keep them *private*
// or *internal* so your library can't be used to breach security by giving
// callers access to unmanaged APIs. Matches *DllImportAttribute* methods
// declared *public* or *non-static*.
//</Desc>
//<HowToFix>
// Change the method's access level and/or declare it static.
//</HowToFix>
Open in the interactive Rules Explorer · All default rules
.NET Framework Usage / System.Runtime.InteropServices: all 3 items
- P/Invokes should be static and not be publicly visible ND2400
- Move P/Invokes to NativeMethods class ND2401
- NativeMethods class should be static and internal ND2402