|
|
Location: Blogs Coder's Corner .NET World |
 |
| Posted by: gmon |
6/17/2007 7:10 AM |
Let’s recap what we know about interoperating with legacy code from .NET. We basically have two methods.
If the legacy code is in the form of a DLL, we can use P/Invoke from any .NET language. We can also use C++ Interop if we are using C++/CLI to access this DLL.
If the legacy code is in the form of a C/C++ source file, then we can use C++ Interop to access it.
No matter which method we choose to interoperate with legacy code, we should consider wrapping up our work into a package that will be useable from any of the .NET languages. This technique involves creating a managed wrapper that acts as a proxy for the legacy native code.
Once this is done, the legacy code will then be available to any other .NET language as a .NET class. So, we tradeoff some more work in the beginning for less work further down the line.
For example, suppose our legacy code is already in the form of a native DLL. We know we can use P/Invoke from any .NET language to access this code. If we also wrap our P/Invoke function declarations into a Visual Basic 2005 module named LegacyCode, then the legacy functions will be available to any .NET language without having to use P/Invoke. Instead the legacy functions will act and look just like .NET member functions. The following Visual Basic .NET code wraps three functions from legacy.dll into a .NET class.
Imports System.Runtime.InteropServices Imports System.Text.StringBuilder
Public Module LegacyCode
Declare Auto Function LegacyFunction Lib "legacy.dll" Alias "LegacyFunction" () As Double
Declare Auto Function LegacyFunction1 Lib "legacy.dll" Alias "LegacyFunction" (ByVal value As Integer) As Integer
Declare Auto Function LegacyFunction2 Lib "legacy.dll" Alias "LegacyFunction2" (ByVal value As Double) As Double
End Module
The functions within this module are now available to any other .NET language. All we have to do is add a reference this module/class in our .NET code and any functions defined within the module are now available.
For example, in C#, after adding a reference to the above module in our project settings, we can now access any of the functions within the module/class by the following code:
private void Form1_Load(object sender, EventArgs e) { Double value; value = LegacyCode.LegacyFunction(); }
Notice how we don’t need to use P/Invoke from C# to access these functions anymore.
The diagram below illustrates some possible scenarios to package our legacy code in a format that will maximize code reuse in .NET.
If the legacy code is already in a native DLL, we can use P/Invoke from any .NET language to create a managed wrapper class.
If the legacy code is already in a DLL that includes an Import LIB, we can use C++/CLI to create a managed wrapper.
If the legacy code is available as source code then we can use C++/CLI to create a managed wrapper.
|
|
| Permalink |
Trackback |
|
|
|
|
|