.net - 在 Win32/COM 方法上调用 PInvoke 时,通常是否会对性能造成明显影响?

标签 .net performance pinvoke marshalling dllimport

我想知道是否有人对在托管 .Net 代码的 Win32 方法上使用 DLLImport/PInvoke 的负面影响有一个不错的解释或概述?

我计划使用各种 Win32 方法,并希望更好地了解这样做的负面影响。

谢谢

布莱恩。

最佳答案

根据MSDN - Calling Native Functions from Managed Code

PInvoke has an overhead of between 10 and 30 x86 instructions per call. In addition to this fixed cost, marshaling creates additional overhead. There is no marshaling cost between blittable types that have the same representation in managed and unmanaged code. For example, there is no cost to translate between int and Int32.

根据我的经验,P/调用 native 函数时肯定会产生开销,但通常不值得担心性能损失。编码成本是需要记住的事情。如果您传递大型结构、字符串等,那么性能成本将很快显现出来。

对于非常频繁调用的 P/Invoke 函数,您可能需要考虑将 [SuppressUnmanagedCodeSecurity] 添加到您的 P/Invoke 函数定义中(请参阅 MSDN - SuppressUnmanagedCodeSecurityAttribute )。这会阻止运行时执行堆栈遍历,以确保调用者具有 UnmanagedCode 权限。当然,在添加此属性之前,请确保您了解安全后果。

关于.net - 在 Win32/COM 方法上调用 PInvoke 时,通常是否会对性能造成明显影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5592572/

相关文章:

c# - 为什么 .NET 中有 5 个版本的定时器类?

c++ - 在字符串c++中查找子字符串的最快方法

c# - 如何将可空类型传递给 P/调用函数

C# 性能 - 使用不安全指针代替 IntPtr 和 Marshal

c# - "A connection attempt failed because the connected party did not properly respond after a period of time"使用 HTTPClient 调用第 3 方 URL

c# - 在每次应用程序启动时在代码滚动中配置 log4net RollingFileAppender

c# - 将 XML 可序列化公共(public)字段重构为自动属性是否会破坏旧实例的反序列化?

c# - 代码剖析 ASP.NET MVC2 应用程序

MySQL 使用索引更新查询速度极慢

c# - 在 C# 中创建一个 STL std::set 并编码到 C++