eBusiness Help
Try The Internet's Most powerful SEO Software For Free
Literally reveals the winning linking structures of any of your competitor's websites
Everything You Will Ever Need To Market A Website On The Internet
Increase Traffic to ANY Website - Whether it is an Enterprise Company, Small Business or Private Website
Manage Reciprocal Links
Create pages of exit links, reciprocal links with related sites, one-way links, a large themed directory or portal site, a news resource, advertisements structured as links, other exit resources, dictionaries, custom search engines, and more!

WebProWorld IT Forum

A little help with inadvertant shutdown
I am currently working on a HP 742C home PC. The problem is it shuts down either durring startup or minutes after startup. I tried Removing the PCI cards...
Click to read more...

CSS and Cache
When I enter a site (like this) the page appears fine, but once I start to navigate through the site, the CSS stylesheet is not being called from the cache and all styling on the site disappears unless I click 'Refresh'.
Click to read more...

Outlook .pst File too Large to Manage
One of my co-workers has grown his Outlook .pst file to 1.99 gigs (apparently he’s very popular). Outlook’s limit for .pst (prior to the 2003 release) is 2 gigs...
Click to read more...



Recent Articles

Microsoft CRM Integration
Microsoft CRM - CRM's answer from Microsoft Business Solutions has an aggressive pricing, going down and making it affordable for small companies. We see cases when Microsoft CRM replaces such traditional CRM systems as Siebel. It is not necessary, that clients decided to replace it themselves - they may be victims of their systems - the example

C++ Function Templates
C++ Function templates are those functions which can handle different data types without separate code for each of them. For a similar operation on several kinds of data types, a programmer need not write different versions by overloading a function. It is enough if he writes a C++ template based function.

LM-X License Management Software for C# .NET
X-Formation announced the release of its LM-X license management software for the C# .NET language. This release extends X-Formation's current lineup of supported languages, which also includes C and C++.

Microsoft CRM Customization: Integration with third party SQL Application/Database
Microsoft CRM - Client Relationship Management package from Microsoft Business Solutions was initially designed to be customizable with Microsoft Visual Studio.Net...

Microsoft CRM Customization secrets – second edition
This article is for advanced Microsoft CRM SDK C# developers. It describes the technique of direct SQL programming, when SDK doesn't have the functionality to do the job.

C# Numerical Library
The IMSL C# Numerical Library is the only mathematical and statistical library written in 100% Microsoft Visual C# .NET for complete compatibility and scalability with the Microsoft .NET Framework. With the IMSL C# Library, developers using Microsoft Visual Studio .NET 2003 can create advanced business analytics applications to help organizations gain valuable insight into business data

Microsoft Great Plains Customization and Development
When Great Plains Software was designing and developing Great Plains Dynamics/Dynamics CS+/eEnterprise - it placed several fundamental principles into the system.

Microsoft CRM Programming Secrets – tips for developers
This article is for advanced Microsoft CRM SDK C# developers. It describes the technique of direct SQL programming, when SDK doesn't have the functionality to do the job. Looks like Microsoft CRM becomes more and more popular, partly because of Microsoft muscles behind it. Now it is targeted to the whole spectrum of horizontal and vertical market clientele.

Avoid C# Memory Leaks with Destructor and Dispose
Here are two classes that allocate resources, the first class needs to implement a destructor and Dispose, but the second class doesn't need to. The difference is that the first class allocates resources in the constructor and doesn't clean them up immediately. In contrast, the second class allocates resources in a member function and carefully frees them before exiting (using a finally block), so the second class author doesn't need to bother writing Dispose and a destructor.

02.02.05


Moving C Structures Into .NET With Custom Marshaling

By Michael Gold

In a world where legacy languages often prevail, we are reluctant to move away from them by reciting the well known mantra, "If it ain't broken, don't fix it". This mantra only gets you so far, until your competitor takes advantage of the newer, faster, more efficient, and more maintainable technologies, and you are left in the dust with your "pristine-aint-broke" legacy code.

One day, you find yourself sitting with your untouched, dust-collecting legacy code, when suddenly your boss tells you, "Convert this behemoth to .NET and do it by next Friday"( the behemoth being anything from C to COBOL). What strategy can you take to alleviate the pain of such a conversion?

Do it in Steps

It is often not necessary, or maybe even not possible, to convert your entire project over to a new technology all at once. Perhaps you can pick a simple interface to your legacy code and have .NET talk to it. If your code is some unmanaged Windows code, the best strategy may be to create a way to marshal information back and forth between the unmanaged interface calls and .NET calls. Well you might say to yourself, "How can I do that? My code contains thousands of methods. I have an API with over a million lines of code? So let's do a simple calculation. I have to convert over a million lines of code (just the interface, now) in two weeks. 1,000,000/ (2 weeks) * (5 programmer-days) * (10 hours) * (3600 seconds) = 2.78 lines/second. Then you say to me", I would have to convert 3 API calls every second and skip lunch." Then you start thinking back on your career dreams of being a simple desk clerk who can take longer lunches.

LinksManager manages reciprocal links, and helps increase website traffic through linking with other like-minded quality sites -> more info

Use a Reverse Engineering Tool/Code Generator

There may be no long lunch in your future, but certainly you'll have time to scarf down a sandwich if you automate the generation of the marshaling code. For this example we will use the UML tool WithClass. Our legacy code is C and we would like to marshal the code to C#. We need to marshal both API calls and structures contained in those calls. In our example we will take the case where we have hundreds of structures and only a few API calls, so we only need to generate the marshaled code for the structures.

Microsoft provides several attributes for marshaling C to C#. Here is an example of marshaling file creation from the kernel32.dll in the windows API.

Listing 1 - WIN32 API for creating a file

[DllImport("Kernel32.dll")]
static extern IntPtr CreateFile(
string filename,
[MarshalAs(UnmanagedType.U4)]FileAccess fileaccess,
[MarshalAs(UnmanagedType.U4)]FileShare fileshare,
int securityattributes,
[MarshalAs(UnmanagedType.U4)]FileMode creationdisposition,
int flags,
IntPtr template);


The idea behind marshaling is that when you "cross-over" from the world of managed code, into the world of unmanaged code, you transfer the same number of bytes in the way the unmanaged world wants to see them. You can marshal just about anything in .NET arrays, structures, and simple types. The problem you will run into with the current marshaling is when you attempt to marshal things like arrays of structures, or structures containing arrays of structures. .NET does not provide a simple way of doing this through attributes. So what do you do? Do you only call managed API's that don't contain complex structures? Do you throw up your hands and say, forget it, I'll just rewrite the unmanaged code and I'll easily have a solution 2 years later? Fortunately, with software, there is always a way.

Flattening your Data

Every simple type, structure, array, or is nothing more than a contiguous set of bytes. An integer consists of 4 bytes (32 bits), and a short consists of 2 bytes (16 bits). An array of shorts with 5 elements can be represented in 10 bytes (2 bytes x 5). An array of structs of size 14 bytes with 3 elements is 42 bytes (14 bytes x 3). No matter what type you are using, in the end, it's just a bunch of bytes. For complex structures with arrays of structures, you can fill a byte array and send it directly to the unmanaged structure. As long as the elements of the byte array are aligned with each position of each type in the structure, the unmanaged structure will be filled correctly. Another words, do your own custom marshaling, rather than relying on the attributes.

Mirroring your Structures in Managed Code

One strategy you might take for creating your structures on the managed side is to have all your classes simply contain a buffer of bytes equal to the number of bytes in the unmanaged structure. Then you simply "generate" a set of properties that are capable of reading and writing the buffer for a particular piece of data in the unmanaged code at the exact position in the buffer corresponding to the unmanaged data. Your class might look something like this:


Listing 2- A flattened class for marshaling managed to unmanaged code

public class Account : CustomMarshalObject
{
MarshalBuffer _buffer = new MarshalBuffer(6);
public short Id
{
get
{
return _buffer.ReadShort(0); // this is the first value in the structure so the offset is 0
}
set
{
_buffer.WriteShort (0);
}
}
public int AccountNumber
{
get
{
return _buffer.ReadInt(2); // Account number starts at an offset of 2 bytes after the Id
}

set
{
_buffer.WriteInt (2);
}
}
}


Our MarshalBuffer class contains a buffer of bytes and has methods to read and write every type in which we are interested. In order to read or write the byte in the correct position, we simply pass the offset into the buffer where the unmanaged byte would sit.

Read the Rest of the Article.


About the Author:
Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, Merrill Lynch. Currently he is a senior consultant at JP Morgan Bank. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems. He can be reached at techsupport@microgold.com

About CProgrammingTrends
A collection of articles and tutorials designed to help C and C variant programmers in their programming work. C Programming Tutorials and advice

CProgrammingTrends is brought to you by:

SecurityConfig.comNetworkingFiles.com
NetworkNewz.comWebProASP.com
DatabaseProNews.comSQLProNews.com
ITcertificationNews.comSysAdminNews.com
LinuxProNews.comWirelessProNews.com
CProgrammingTrends.comITmanagmentNews.com


-- CProgrammingTrends is an iEntry, Inc. publication --
iEntry, Inc. 880 Corporate Drive, Lexington, KY 40503
2005 iEntry, Inc.  All Rights Reserved  Privacy Policy  Legal


archives | advertising info | news headlines | free newsletters | comments/feedback | submit article

C Programming Tutorials and advice CProgrammingTrends News Archives About Us Feedback CProgrammingTrends Home Page About Article Archive News Downloads WebProWorld Forums Jayde iEntry Advertise Contact