Head-Spinning Continued: The XCopy Port

From Kate Gregory’s Codeguru column, “Using Visual C++ .NET“.

–>

This column is the fifth in a series about interop between new managed and old unmanaged code: the choices you have and the consequences of those choices. So far you’ve met the legacy class and seen why you almost certainly need FullTrust permissions, wrapped the legacy class as a COM component and accessed it from unmanaged and managed code, wrapped the legacy class as a DLL and accessed it with P/Invoke, and accessed that same DLL without P/Invoke. Only in C++ can you call directly to unmanaged code from managed code.

That’s the promise of It Just Works: you can take a piece of C++ code that worked as unmanaged code, and compile it to intermediate language and it will work. No matter what it calls or is linked to, it will work when you recompile it as managed code. Statically or dynamically linked, to MFC, ATL, the STL, your own libraries — it will all work.

The next way to make that old legacy C++ code available to managed code is to make it managed code — and it’s a lot less work than you might expect. I like to call it the xcopy port, using the same concepts as xcopy deployment. The xcopy utility, for those who’ve never met it, is a DOS command that copies several files at once. An xcopy deployment is one that consists simply of copying the assemblies to the target machine, with no further configuration, registration, or installation. A xcopy port, then, is one that involves little more than simply copying your code to a new project and recompiling it.

All you need to do is create a managed project (I created a console application so I could write a test harness,) copy all the .cpp and .h files from the legacy library folder into the new project folder, then add them to the project. From within Visual Studio, right-click the project in Solution Explorer and choose Add, Add Existing Item. Add all the files you just copied.

Then use your new managed code just as you would expect to. For example, here is a managed main that uses ArithmeticClass:

#include "stdafx.h"

#using <mscorlib.dll>

#include "LegacyArithmetic.h"
using namespace System;

int _tmain()
{
    ArithmeticClass a;
    Console::Write(S"1 + 2 is ");
    Console::WriteLine(__box( a.Add(1,2)));
    return 0;
}

ArithmeticClass is not a managed (garbage-collected) class, but there’s no problem using it from this managed code. The resulting exe is a .NET assembly of intermediate language. You can take a look at it with ILDASM and check the code for any of the methods yourself. For example, the code for Add looks like this:

.method public static float64 modopt(
  [mscorlib]System.Runtime.CompilerServices.CallConvThiscall)
        ArithmeticClass.Add( valuetype ArithmeticClass*
  modopt([Microsoft.VisualC]Microsoft.VisualC.IsConstModifier)
  modopt([Microsoft.VisualC]Microsoft.VisualC.IsConstModifier) A_0,
                            float64 num1,
                            float64 num2) cil managed
{
  .vtentry 45 : 1
  // Code size       6 (0x6)
  .maxstack  2
  IL_0000:  ldarg.1
  IL_0001:  ldarg.2
  IL_0002:  add
  IL_0003:  br.s       IL_0005
  IL_0005:  ret
} // end of method 'Global Functions'::ArithmeticClass.Add

Just like that, the class that was originally defined in unmanaged code is now in managed code. But it’s not managed data. It’s not garbage collected. You can create instances on the stack or the heap as you prefer, and you have to manage the memory yourself. This C++ program is able to use it even though it’s unmanaged data, but other managed languages such as C# cannot. If all you wanted to do was write your new application in Managed C++, this technique works wonderfully. If you want to create something for those other languages too, tune in next time!

About the Author

Kate Gregory is a founding partner of Gregory Consulting Limited (www.gregcons.com). She is the MSDN Regional Director for Toronto, Canada. Kate’s experience with C++ stretches back to before Visual C++ existed. She is a well-known speaker and lecturer at colleges and Microsoft events on subjects such as .NET, Visual Studio, XML, UML, C++, Java, and the Internet. Kate and her colleagues at Gregory Consulting specialize in combining software develoment with Web site development to create active sites. They build quality custom and off-the-shelf software components for Web pages and other applications. Kate is the author of numerous books for Que, including Special Edition Using Visual C++ .NET.


# # #

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read