Let us say that I am accessing a third-party library, for which the documentation states that I can use pInvoke or create an interop library and use COM. What is the difference between these two techniques, and why might I choose one over the other?
P/Invoke is a technology that allows you to access structs, callbacks, and functions in unmanaged libraries from your managed code. Most of the P/Invoke API is contained in two namespaces: System and System.
* The term PInvoke is derived from the phrase "Platform Invoke". PInvoke signatures are native method signatures, also known as Declare statements in VB.
C++ Interop is also known as implict PInvoke and informally referred to as It Just Works. This mechanism consists of wrapping a native C++ class so that it can be consumed by C# code. More details on this method can be found here. COM Interop is a mechanism specifically for exposing COM components to a .
P/Invoke is used to call plain-C APIs (like most of the Win32 API). COM interop is used to call COM objects.
You might create a C++ COM wrapper around a C API and then use COM interop to call your wrapper if the number of API calls is relatively high (and you can use the COM wrapper to encapsulate them into just one or two calls). This is because managed-native interop can be relatively expensive and it's good to minimise the number of transitions. Though actually I would say using C++/CLI to create the wrapper would probably be a little more friendly for the C# side of thing (looking at SlimDX, for example, which is a C++/CLI wrapper around a COM API (DirectX)).
Having said that, unless you have a specific performance problem, I would just use whichever method is more natural for the API you're trying to call: if it's a C API (like the Win32 API is) then use P/Invoke. If it's COM-based, then use COM interop.
PInvoke uses the dynamic linking mechanism for bringing external code into the executing process. Dynamic linking libraries (DLLs) must have the same target architecture as the calling application, so there is no ability to make cross calls from 64-bit to 32-bit or vice versa. Instead the DLL is mapped into the caller's address space and executed in process.
COM, DCOM, COM+, and ActiveX are all based on interprocess communications libraries, but can sometimes devolve into a simple DLL load. COM linked objects are related, but not identical to CORBA objects, but while CORBA evolved its own object locator, the COM implementation is still loosely based on Sun Microsystems RPC and XDR libraries with extensions for the object oriented features of COM. COM objects are referenced not by DLL, but by a GUID which is used to look up the object class and query its interfaces. The object code usually runs in a separate process, and possibly on a separate server.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With