本文介绍了“管理"和“管理"之间的区别和“不受管理的"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在谈论 .NET 时有时会听到/读到它,例如托管代码"和非托管代码",但我不知道它们是什么以及它们的区别是什么.根据定义,它们有什么区别?使用其中任何一个的后果是什么?这种区别是否仅存在于 .NET/Windows 中?

I hear/read about it sometimes when talking about .NET, for example "managed code" and "unmanaged code" but I have no idea what they are and what are their differences. What are their difference, by definition? What are the consequences of using either of them? Does this distinction exist in .NET/Windows only?

推荐答案

托管代码

托管代码是 Visual Basic .NET 和 C# 编译器创建的.它在 CLR(公共语言运行时)上运行,它提供垃圾收集、运行时类型检查和引用检查等服务.因此,可以将其视为我的代码由 CLR 管理."

Visual Basic 和 C# 可以生成托管代码,因此,如果您正在使用其中一种语言编写应用程序,那么您正在编写由 CLR 管理的应用程序.如果您使用 Visual C++ .NET 编写应用程序,您可以根据需要生成托管代码,但这是可选的.

Visual Basic and C# can only produce managed code, so, if you're writing an application in one of those languages you are writing an application managed by the CLR. If you are writing an application in Visual C++ .NET you can produce managed code if you like, but it's optional.

非托管代码直接编译为机器代码.因此,根据该定义,由传统 C/C++ 编译器编译的所有代码都是非托管代码".此外,由于它编译为机器代码而不是中间语言,因此不可移植.

Unmanaged code compiles straight to machine code. So, by that definition all code compiled by traditional C/C++ compilers is 'unmanaged code'. Also, since it compiles to machine code and not an intermediate language it is non-portable.

没有免费的内存管理或 CLR 提供的任何其他东西.

No free memory management or anything else the CLR provides.

由于您无法使用 Visual Basic 或 C# 创建非托管代码,因此在 Visual Studio 中,所有非托管代码都是用 C/C++ 编写的.

Since you cannot create unmanaged code with Visual Basic or C#, in Visual Studio all unmanaged code is written in C/C++.

由于 Visual C++ 可以编译为托管或非托管代码,因此可以在同一个应用程序中混合使用这两种代码.这模糊了两者之间的界限并使定义复杂化,但值得一提的是,您知道如果您使用第三方库以及一些编写不当的非托管代码,您仍然可能存在内存泄漏.

Since Visual C++ can be compiled to either managed or unmanaged code it is possible to mix the two in the same application. This blurs the line between the two and complicates the definition, but it's worth mentioning just so you know that you can still have memory leaks if, for example, you're using a third party library with some badly written unmanaged code.

这是我通过谷歌搜索发现的一个例子:

Here's an example I found by googling:

#using <mscorlib.dll>
using namespace System;

#include "stdio.h"

void ManagedFunction()
{
    printf("Hello, I'm managed in this section
");
}

#pragma unmanaged
UnmanagedFunction()
{
    printf("Hello, I am unmanaged through the wonder of IJW!
");
    ManagedFunction();
}

#pragma managed
int main()
{
    UnmanagedFunction();
    return 0;
}

这篇关于“管理"和“管理"之间的区别和“不受管理的"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-18 23:14