29

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 to make use of various Win32 methods and would like to have a greater understanding on the negative implications of doing so.

Thanks,

Brian.

Brian Scott
  • 9,221
  • 6
  • 47
  • 68

2 Answers2

37

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.

Lee Berger
  • 1,234
  • 14
  • 21
  • 5
    .NET Core removes the "partial trust" functionality in the CLR, so `[SuppressUnmanagedCodeSecurity]` isn't necessary anymore (in fact it's removed from .NET Core completely): https://github.com/dotnet/runtime/issues/4514 – Dai May 11 '20 at 09:46
  • Would it help if one creates a C++/CLI wrapper library that does the native calls? – nikeee May 22 '20 at 06:33
4

Here are some issues I see with PInvoke:

  • Parameter marshaling can be expensive, depending on the data type (blittable / non-blittable)
  • Correct parameter marshaling is often not very intuitive
  • PInvoke does not provide any compile time security. One can easily misspell DLL or function names easily without the compiler complaining.

If you plan to use lots of unmanaged functions I would create a mixed DLL (Mixed (native and managed) assemblies) rather than declaring a bunch of PInvokes.

malat
  • 12,152
  • 13
  • 89
  • 158
Florian Greinacher
  • 14,478
  • 1
  • 35
  • 53
  • thanks for the feedback. I was hoping for some examples of the expense. Is that something you have previously discovered? – Brian Scott Apr 08 '11 at 13:36
  • Sorry Brian, those are just my subjective experiences with PInvoke. I cannot provide any concrete benchmarks. Have a look at http://msdn.microsoft.com/en-us/library/ky8kkddw.aspx – Florian Greinacher Apr 08 '11 at 13:45