Interoperability in C#

Programming has been around for some time and we haven’t always had the .Net Framework to make our lives as programmers and support engineers so easy. When we program within the confines of the .Net Framework, we are building managed code. Managed code is compiled in Bytecode. Prior to the .Net Framework we programmed in unmanaged code. Meaning we compiled it directly into a native operating system binary. In most cases, it became a .dll or COM (Component Object Model). Since many systems we create today (managed code) will need to use some of the older code (unmanaged code) there needs to be an interface between to 2 types of code. This interface is called PInvoke (Platform Invoke) which utilizes the DllImport attribute.

Before the nice SMTP .net libraries, there was a popular email program called BLAT. BLAT is coded in unmanaged code. Below is an example of using BLAT with C#, which is managed code.

[sourcecode language="csharp" padlinenumbers="true" autolinks="false" gutter="false" toolbar="false"]
using System.Runtime.InteropServices;
[DllImport("blat.dll", CharSet = CharSet.Ansi)]
public static extern int Blat(int argc, string[] argv);
[DllImport("blat.dll", CharSet = CharSet.Ansi)]
public static extern short Send(string cmd);
string BlatCmd = "- -to to@noplace.dom " +
                 "-from from@nowhere.dom " +
                 "-subject Test Email " +
                 "-body Hello from nowhere " +
                 "-server IP.IP.IP.IP";
short returnCode = Send(BlatCmd);       

When the Send method is called it uses the Win32 API within the blatt.dll to send the email.

There are many such examples in the real world so I recommend testing out this area of programming at some point, early in your career.

Leave a Comment

Your email address will not be published.