What are the disadvantages of using P / Invoke

I am already working well with a .net card. There were some situations around this time, I used P / Invoke to perform actions that I could not do with managed code.

However, I did not know exactly what his real flaws were. This was also the reason I tried not to use it as much as possible.

If I google, then I find various messages about this, some paint a disastrous picture and recommend never to use it. What are the main flaws and problems of an application that uses one or more P / Invoke calls and when they are applied. (and not in terms of performance, more in that "it is impossible to execute from a network resource")?

+4
source share
2 answers
  • Marching between managed / unmanaged types has additional overhead
  • Doesn't work in trust
  • It is not completely intuitive and can lead to subtle errors, such as leaking pens, memory corruption, ...
  • It may take some time before getting it right if you look at the exported C. function.
  • Problems migrating from x86 to x64
  • When something goes wrong, you can't just go into unmanaged code to debug and understand why you get exceptions. You cannot even open it in Reflector :-)
  • It limits cross-platform compatibility (i.e. you cannot run on Linux if you rely on a Windows-only library).

Conclusion: Use only if there are no managed alternatives or critical applications where only unmanaged libraries exist to provide the required speed.

+13
source

There are three different scenarios in which you use P / Invoke, and in each of them there are (or not) different flaws.

  • You need to use Windows features that are not provided in the .NET Framework. Your only choice is P / Invoke, and the disadvantage you are experiencing is that your application will now only run on Windows.

  • You need to use the C-style DLL provided by someone else and there is no manageable equivalent. Now you need to deploy the DLL with your application, and you will have problems with sorting time and possible hangs in the function declaration (for example, IntPtr / int), sorting strings and other things that people find complicated.

  • You have old code that you wrote or manage, and you want to access it from managed code without porting it. Here you have all the problems (2), but you have the opportunity to port it. I am going to argue that you will be causing more errors by porting them than you are using P / Invoking. You can also cause a big problem with punching if the code you carry causes a lot of calls to your own code, like CRT.

My bottom line is that while P / Invoke is nontrivial, telling people this is bad advice. Once you fix this, assembly costs at runtime are all that remains. This may be less than the runtime cost you get when porting the code.

+4
source

All Articles