在Win32/COM方法上调用PInvoke时,通常会明显降低性能吗? [英] Is there generally a noticeable performance hit when calling PInvoke on Win32 / COM methods?

查看:132
本文介绍了在Win32/COM方法上调用PInvoke时,通常会明显降低性能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm wondering whether anyone has a decent explanation or overview on the negative aspects of using DLLImport / PInvoke on Win32 methods from managed .Net code?

我计划使用各种Win32方法,并希望对这样做的负面影响有更多的了解.

I plan to make use of various Win32 methods and would like to have a greater understanding on the negative implications of doing so.

谢谢

布莱恩.

推荐答案

根据 MSDN-从托管代码调用本机函数

PInvoke每个调用的开销为10到30条x86指令.除此固定成本外,封送处理还会产生额外的开销.在托管和非托管代码中具有相同表示形式的可绑定表类型之间没有封送处理成本.例如,在int和Int32之间进行转换无需花费任何费用.

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/调用本机函数肯定会产生开销,但是通常性能下降是不值得担心的.编组成本是要记住的事情.如果您传入的是大型结构,字符串等,那么性能成本将很快显示出来.

In my experience, there definitely is an overhead when P/Invoking native functions, but usually the performance hit isn't worth worrying about. The marshaling cost is something to keep in mind. If you are passing in large structures, strings, etc. then the performance costs will quickly show.

对于经常调用的P/调用函数,您可能需要考虑在P/Invoke函数定义中添加[SuppressUnmanagedCodeSecurity](请参阅

For P/Invoked functions that are called very frequently, you may want to consider adding [SuppressUnmanagedCodeSecurity] to your P/Invoke function definitions (see MSDN - SuppressUnmanagedCodeSecurityAttribute). This stops the runtime from doing a stack walk to ensure the caller has UnmanagedCode permission. Of course, make sure you understand the security ramifications before adding this attribute.

这篇关于在Win32/COM方法上调用PInvoke时,通常会明显降低性能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆