Why is COM interop preferred over P/Invoke in .NET?

前端 未结 1 720
别那么骄傲
别那么骄傲 2021-02-06 07:59

In our project we are reusing lot\'s of Delphi code through COM in our asp.net application.

Like this: legacy delphi dll => delphi COM wrapper => .Net interop => asp.net

相关标签:
1条回答
  • 2021-02-06 08:59

    Pinvoke is a very nice tool but it certainly is no substitute for COM. Pinvoke only supports simple functions with a C syntax, COM lets you implement an object model. Take the classes in the Microsoft.Office.Interop namespaces for example, they are all pure COM classes with no wrappers. Doing Office interop with pinvoke would be excruciatingly painful.

    Another core problem with pinvoke that it is typically the burden of the client programmer to write the declarations. The person least likely to get them right. A COM author can publish an auto-generated type library, much like metadata in a .NET assembly. Drastically eliminating the odds for mistakes and no work needed by the client programmer beyond Project + Add Reference.

    Addressing your bullets:

    • checked out code will always use the correct dll‘s instead of the last registered COM
      You are still subject to the vagaries of Windows finding the proper DLL. The only good way to avoid accidents is to store the DLL in the same directory as the EXE. Which is quite possible in COM as well, all you have to do is create an empty file with the name yourapp.exe.local

    • Multiple versions can run side by side on the servers (for instance: DEV, TEST and QA)
      Not a problem in COM either, using the above technique or by using a reg-free manifest

    • No more COM registrations hassle
      Use a reg-free manifest so no registration is required. Very simple to do, just set the Isolated property of the reference to True.

    • Much faster than COM communication (articles I read indicate a 30% speed increase)
      It is much slower than COM. You can incur an extra cost by making late-bound COM calls through IDispatch, that's roughly as expensive as using Reflection to make the call.


    There's a third way to do native code interop: writing a managed class wrapper in the C++/CLI language. The technique heavily used in the .NET framework, particularly in mscorlib.dll, System.Data and PresentationFramework, assemblies that have strong dependencies on native code. Not however very suitable for Delphi, it works best for native code that can easily be called from C or C++.

    0 讨论(0)
提交回复
热议问题