C++
Interop, also known as “It Just Works”, is only available if you
are using C++/CLI. It is my preferred way of accessing legacy C/C++
code. The basic idea is that things should work as they have always
worked before .NET came along. In other words, if you want to access
functions within a DLL from C++/CLI, you perform the same steps as if
you were using Visual C++ 6.0.
To
illustrate how this is done, suppose you have access to a legacy
library packaged in a DLL called MathDLL.dll. This is the same
library that I used earlier to illustrate how to use P/Invoke to
access functions in a DLL.
Now
suppose you use Visual Studio 2005 to create a new project called
MathDLLUserIJW that is a C++/CLI console application that uses
functions from MathDLL. Instead of using P/Invoke to access these
functions, we will use C++ Interop instead. Here's how it works:

- From
the Solution Explorer, right click the MathDLLUserIJW project and
select properties. Make sure the Configuration is set to “All
Configurations”. Go to the C/C++ -->General properties and enter the path to the header file from the
MathDLL project to the “Additional Include Directories”.
- Copy
the legacy DLL to the same location as the executable for
MathDLLUserIJW.
And
that’s it! It’s pretty much the exact same way to use a DLL from
Visual C++ 6.0. In other words, you just do things the way you've
always done it in the past and “It just works”!
What
if the legacy C/C++ code is in the form of a static LIB?
Unfortunately, you can’t just link in a static LIB built from
Visual C++ 6.0 with an application built from C++/CLI. But that’s
always been the case – you couldn’t link in a static LIB built
from Visual C++ 5.0 with an application built from Visual Studio C++
6.0 either. Static libraries aren’t meant to be portable. You
can’t mix libraries built to run on different C/C++ runtimes. They
all must be compiled with the same compiler.
If
we have the source code to this static library, we would just
recompile the source code in the Visual Studio 2005 C++/CLI compiler
(with the /CLR switch) and link it with our C++/CLR application code.
It just works!
So,
now we know two methods of accessing legacy code in the .NET
environment. We can use P/Invoke from any .NET language to access
legacy code that is packaged in a DLL. If we are using C++/CLI, then
we can also use C++ Interop to access legacy code that is packaged in
a DLL or if we have access to the legacy C/C++ source code itself.