非托管代码¶
ID: cs/unmanaged-code
Kind: problem
Security severity:
Severity: recommendation
Precision: high
Tags:
- reliability
- maintainability
Query suites:
- csharp-security-and-quality.qls
Microsoft 为源代码定义了两大类。托管代码编译成字节码,然后由虚拟机执行。非托管代码直接编译成机器代码。所有 C# 代码都是托管的,但可以调用外部非托管代码。此规则查找由非托管代码实现的 extern
方法。与非托管代码相比,托管代码有很多优势,例如由虚拟机执行的内置内存管理以及在更广泛的体系结构上运行编译程序的能力。
建议¶
考虑是否可以使用 C# 实现非托管 extern
方法。
示例¶
此示例显示了一个函数,该函数在被点击时显示一个消息框。首先显示非托管代码,然后显示由托管代码执行的相同函数。
// example of using unmanaged code
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public partial class UnmanagedCodeExample : Form
{
[DllImport("User32.dll")]
public static extern int MessageBox(int h, string m, string c, int type); // BAD
private void btnSayHello_Click(object sender, EventArgs e)
{
MessageBox(0, "Hello World", "Title", 0);
}
}
// the same thing in managed code
using System;
using System.Windows.Forms;
public partial class ManagedCodeExample : Form
{
private void btnSayHello_Click(object sender, EventArgs e)
{
MessageBox.Show("Hello World", "Title");
}
}