Click here to Skip to main content
15,867,568 members
Articles / Productivity Apps and Services / Microsoft Office
Tip/Trick

Interoperability with .NET Platform

Rate me:
Please Sign up or sign in to vote.
4.47/5 (7 votes)
22 Feb 2015CPOL5 min read 25.8K   178   9   7
Communication between .NET and other programming languages

Introduction

This tip explains how Microsoft.NET is built from scratch to be interoperable with different languages like C, C++ and COM based software.

Whether your application is written with managed code or not, the .NET platform provides new mechanisms that make communication possible between your application and others programming language.

Java programming language is built to be a portable language, it can be deployed anywhere: ‘Run once and deploy anywhere’. This portability is due to a bytecode (portable code or intermediate code) designed for efficient execution by a compiler.

The most important thing to Java architects was the portability factor, Java was made to work alone and run on multiple platform, integrating this language with other programming languages was not simple even if there are some implementations Like CORBA which enable Java to talk with C++. The problem with CORBA was its complexity, the developer must learn a third language called IDL (intermediate description language)!

Microsoft thinks differently, .NET architects think that the most important aspect is interoperability between different applications and programming languages and that’s why .NET provides a full support of XML in its core components, for example ADO.NET and the Dataset class which strongly support XML and XML web services introduced in 2001 based on SOAP protocol.

All .NET languages can work together easily whatever is their type:

  • Object programing language (C#)
  • Functional programming language (F#)
  • Dynamic language like Iron Ruby or Iron python

Java architects understand that interoperability with other languages is important because companies have many applications written with different languages and we need a powerful platform that make communication between these applications very easy.

Background

This tip may be useful for developers who have some basics in C# and .NET.

Using the Code

In the next paragraph, we will explain two different scenarios about interoperability:

  1. COM interoperability
  2. P/Invoke

Communication Between Managed Code and Com Based Software

Component Object Model (COM) is a binary-interface standard for software components introduced by Microsoft in 1993. It is used to enable inter-process communication and dynamic object creation in a large range of programming languages. COM is the basis for several other Microsoft technologies and frameworks, including OLE, OLE Automation, ActiveX, COM+, DCOM, the Windows shell, DirectX, UMDF and Windows Runtime

In simple words, COM creates a bridge between managed code and unmanaged code, for example, if we have a C# client and a C++ server, COM transfers messages between the client and the server transparently without the need of an intermediate language.

Now, let’s write some code:

  1. We want to consume a COM library (Office component) with managed Code (C#)
    1. The client is written with managed Code (VB.NET).
    2. The server is written with unmanaged Code (Microsoft Office Component)

Through this demonstration, we will develop a C# client that can interact with Microsoft Office Word (which is a Com software written in C++), this application allows us to integrate Office spelling correction in our .NET application.

Steps

  • Open Visual Studio (I am using VS 2013).
  • Choose Visual Basic and create a Windows Form application.
  • Visual Studio will generate a Windows Forms project for you.
  • Add a richTextBox and a button.
  • Right click on solution Explorer => Add reference => choose ‘Com’.
  • Find a library called “Microsoft.Office.Interop.Word"
  • Add a new class and call it Spelling.vb and paste this code:
    VB.NET
    Imports Microsoft.Office.Interop
    Public Class Spelling
        Public Function CorrectText(ByVal text As String) As String
     Dim message As String = text
    'instantiate a Word app
     Dim wordApplication As Word.Application = New Word.Application
    'don't confuse things by showing the app
     wordApplication.Visible = False 
     wordApplication.Documents.Add()
            Dim range As Word.Range
            range = wordApplication.ActiveDocument.Range
            'dump in the TextBox.text
            range.InsertAfter(text)
            Dim s As Word.ProofreadingErrors
            s = range.SpellingErrors
            If s.Count > 0 Then
                Dim incorrectWord As String
                For i As Integer = 1 To s.Count
                    'incorrect Word
                    incorrectWord = s.Item(i).Text
                    'Get the correct spelling
    Dim CorrectWord As String = wordApplication.GetSpellingSuggestions(incorrectWord).Item(1).Name
    'Correct Word
    message = message.Replace(incorrectWord, CorrectWord)
           Next
         'Free Memory and destroying Word instance
         wordApplication.Quit(False)
            End If
            Return message
        End Function
    End Class
  • Double Click on the button ‘btnSpellingCorrection’ and paste this code:
    VB.NET
    Spelling spelling = new Spelling();
    'Get the spelling correction from Microsoft Office
    richTextBox.Text=spelling.CorrectText(richTextBox.Text);       

Voilà :), communication between the managed client (VB.NET) and the unmanaged server (Office Word component) does not require any extra work because the CLR takes in charge the marshalling of Data between these two technologies at runtime.

There is no need to use intermediate language or anything else, we just add Reference to the COM library as if it is a managed Library.

Communication with P/Invoke

Platform Invocation Services (P/Invoke) is a feature of Common Language Infrastructure implementations that enables managed code to call native code.

We will demonstrate how we can invoke native code that is implemented in a DLL from managed code, the scenario is simple, we will consume a function found in the Windows kernel called GetComputerName, this function exists on the Kernel32.DLL, it is written with the C language and we will call it from C# 4.0. This function returns the name of the computer machine.

Steps

  • Open Visual Studio.
  • Choose Visual C# and create a Windows Form application.
  • Visual Studio will generate a Windows Forms project for you.
  • Paste this code just after the class Definition
  • The function must be declared with the static and extern C# keywords.
  • The DllImport attribute allows you to specify the name of the DLL that contains the method. The common practice is to name the C# method the same as the exported method, but you can also use a different name for the C# method.
C#
 [DllImport("kernel32.DLL")]
public static extern bool GetComputerName( StringBuilder computerName, ref int size);
  • Then, to test your code, you can write this:

C#
//Win32 API Version
StringBuilder buf = new StringBuilder(255);
int size = buf.Capacity;
GetComputerName(buf, ref size);
MessageBox.Show(buf.ToString());

The compiler will execute the function even if the developer has just written the signature of the function, there isn't any extra implementation of any intermediate code, the CLR takes in charge the communication between C# and C language.

Summary

Through this tip, we have seen two scenarios explaining how .NET can communicate with other technologies and programming languages:

  1. Communication between managed Code and Com based software (first demo)
  2. Communication between managed Code and native Code (second demo)

The opportunities are unlimited due to the number of languages supported by .NET, besides, there are a lot of other modern technologies like Web services, Windows Communication Foundation and Web API which introduce what we call ‘Software as services’ which will be the subject of another article.

Thank you for reading, try to download the source code and do not hesitate to leave your questions, comments and thanks if you want to.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
France France
Sofiene Rabhi is Microsoft certified professional in C# ,HTML 5 and JavaScript, Asp.net and Microsoft Silverlight, consultant, trainer specializing in application development with Microsoft technologies, including c#, Vb.net, and Microsoft Azure.

Comments and Discussions

 
Questionjava can do interopt... Pin
marc borgers23-Feb-15 9:33
marc borgers23-Feb-15 9:33 
AnswerRe: java can do interopt... Pin
Soufiane Rabhi 23-Feb-15 10:00
Soufiane Rabhi 23-Feb-15 10:00 
GeneralRe: java can do interopt... Pin
marc borgers23-Feb-15 18:00
marc borgers23-Feb-15 18:00 
GeneralRe: java can do interopt... Pin
Soufiane Rabhi 23-Feb-15 20:55
Soufiane Rabhi 23-Feb-15 20:55 
GeneralRe: java can do interopt... Pin
marc borgers23-Feb-15 21:18
marc borgers23-Feb-15 21:18 
ok
GeneralMy vote of 5 Pin
Humayun Kabir Mamun23-Feb-15 1:53
Humayun Kabir Mamun23-Feb-15 1:53 
GeneralRe: My vote of 5 Pin
Soufiane Rabhi 23-Feb-15 9:58
Soufiane Rabhi 23-Feb-15 9:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.