tags:

views:

55

answers:

1

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?

+4  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.

Dean Harding
So are you saying that under the hood, COM interops are making doing pinvokes themselves? And that COM is just a friendly wrapper?
Grant
No, COM interop and P/Invoke are different and one is not implemented in terms of the other. What I was saying in my second paragraph is that if the C API is "chatty" and requires lots of function calls, you could make a COM wrapper (in C++) and call *the wrapper* from C# to reduce the number of managed-native transitions. I suspect that is what the documentation for your library is suggesting.
Dean Harding