c# - C# 中的 NativeMethods 类有什么作用?

标签 c# pinvoke native-methods

<分区>

Possible Duplicate:
Is the class NativeMethods handled specially in .NET?

我正在开发一个 C# 项目,该项目为某些功能调用一些非托管 C++ 代码。我发现了 fxCop,它提示我从非托管库中包含函数的方式。

它建议使用此处解释的 NativeMethods 类之一:

http://msdn.microsoft.com/en-us/library/ms182161%28v=vs.80%29.aspx

我读过它,但我不能说我理解它到底做了什么以及使用它有什么好处。如果有人能向我解释“此类不抑制非托管代码许可的堆栈遍历”的含义,我将非常高兴。和“此类抑制非托管代码权限的堆栈遍历。”

编辑:我真正想知道的是它如何影响我的代码。我已经阅读了它在 MSDN 上所说的内容,显然它对某些人来说已经足够了,但对我来说太高了,无法理解。这就是为什么我要求进行一些详细说明。

最佳答案

本文的 Visual Studio 2012 版本包含更多解释,

http://msdn.microsoft.com/en-us/library/ms182161(v=vs.110).aspx

To fix a violation of this rule, move the method to the appropriate NativeMethods class. For most applications, moving P/Invokes to a new class that is named NativeMethods is enough.

However, if you are developing libraries for use in other applications, you should consider defining two other classes that are called SafeNativeMethods and UnsafeNativeMethods. These classes resemble the NativeMethods class; however, they are marked by using a special attribute called SuppressUnmanagedCodeSecurityAttribute. When this attribute is applied, the runtime does not perform a full stack walk to make sure that all callers have the UnmanagedCode permission. The runtime ordinarily checks for this permission at startup. Because the check is not performed, it can greatly improve performance for calls to these unmanaged methods, It also enables code that has limited permissions to call these methods.

However, you should use this attribute with great care. It can have serious security implications if it is implemented incorrectly..

For information about how to implement the methods, see the NativeMethods Example, SafeNativeMethods Example, and UnsafeNativeMethods Example.

关于c# - C# 中的 NativeMethods 类有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12742061/

相关文章:

c# - 如何从 T 的类型中获取 T 的类型?

c# - 为什么从针对任何 CPU 的 C# 项目调用时,此代码会抛出 System.AccessViolationException?

c# - 如何将 C++ std::future 返回值适配为 C# System.Threading.Tasks.Task?

android - 从 java 调用 native 方法时的 Libc SIGSEGV

c# - TestDriven.NET 和 native C 库

javascript - 在 apply 的重新声明中调用 Function.prototype.apply (Javascript)

c# - 无法使用 Simple Injector 注册 Api Controller?

c# - 使用 R 对 DocumentDB 资源进行访问控制

c# - 从 File.Copy 中排除系统硬链接(hard link)

dllimport 无法定位 dll,即使它在 PATH 中