Is there generally a noticeable performance hit when calling PInvoke on Win32 / COM methods?

前端 未结 2 351
清酒与你
清酒与你 2021-02-01 03:42

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?

I plan t

2条回答
  •  生来不讨喜
    2021-02-01 04:21

    According to 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.

    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.

    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.

提交回复
热议问题