Click here to Skip to main content
Licence CPOL
First Posted 25 Apr 2001
Views 88,385
Bookmarked 19 times

Cross language inheritance in .NET

By | 15 Oct 2001 | Article
An introduction to cross-language inheritence in .NET.

Introduction

The introduction of .NET brings makes language development simpler than ever. We no longer need to worry about using ATL wrappers in C++ to access VB components, or calling conventions when attempting to interface with FORTRAN code. All .NET enabled languages are now first class entities and interoperate seamlessly, allowing disparate systems to work together more easily than ever, and also allowing developers with different skill sets to work harmoniously together on projects.

Creating a .NET component

Creating a component in one language that can be used by another language is very simple. Use the Visual Studio.NET Wizard to create a class library in your favourite .NET language, compile it, and you are done.

For example, we will create a simple class in C# that exposes two methods:

namespace MyCSClass
{
	using System;

	public class CSClass
	{
		public CSClass() { }

		// returns the length of the passed string
		public int MyMethod(string str)
		{
			return str.Length;
		}

		// returns n squared
		virtual public int MyVirtualMethod(int n)
		{
			return n*n;
		}
	}
}

The first method, MyMethod, takes a string object and returns its length. The second method is virtual, and returns the square of the number passed in. Assume that we have compiled this component to MyCSClass.dll.

Using a .NET component in managed C++

To consume this component using managed C++ we need to first import the assembly into our program:

#using "MyCSClass.dll"

That's it. No typelibs, no .def files, no ATL headers. We simply use the #using statement (and ensure the dll is in the compilers search path) and let the compiler do the rest.

Once we have imported the class we can then use the using declaration to save typing:

using namespace MyCSClass;

Note the difference here: #using is for importing an assembly into your project. using specifies the namespace we will be working with, and merely saves typing.

Actually consuming the class is the same as using any other managed reference type in .NET:

CSClass *cs = new CSClass();

int result;
result = cs->MyMethod("Hello World");  // will return 11
result = cs->MyVirtualMethod(2);       // will return 2 squared

Cross language inheritence

Cross language interoperability goes further than simply easing the use of components written in different languages. We can also inherit new classes from components written in other languages, without needing the original source code for the component.

Imagine you have bought, or otherwise acquired some super-cool component that you love using, but that you wish had one or two more features, or that it did something slightly different. In .NET you can inherit a new class from that component to create a new component that works exactly how you would like. You aren't creating a wrapper for the component: you are creating a new component that derives its properties, methods and fields and that can override the old component's virtual methods and add new methods.

Back to our example. The method CSClass::MyVirtualMethod is virtual, so let's declare a new C++ class that is derived from this C# class, and override that virtual method

__gc class CPPClass : public MyCSClass::CSClass
{
public:
	// returns the cube of the given number
	virtual int MyVirtualMethod(int n)
	{
		return n*n*n;
	}
};

We have overridden CSClass::MyVirtualMethod with our new method that returns the cube, not the square, of the given number. Once we compile the code we we have a new C++ component that overrides the virtual method in the C# class, and also has the non-virtual MyMethod() function.

CPPClass *cpp = new CPPClass();

int result;
result = cpp->MyMethod("Hello World"); // will return 11
result = cpp->MyVirtualMethod(2);      // Will output 2 cubed, not 2 squared

The accompanying download to this article contains a C# and a VB.NET component that is consumed by, and inherited by, a C++ component.

Conclusion

Cross language interoperability allows you to extend 3rd party components with your own functionality in an object oriented fashion. You can easily work with components in any CLS compliant language, and when debugging you are able to step through function calls between components and between languages in the same application. Exception handling is also consistent across languages. If a component in one language throws an exception it can be caught and handled by code written in another language. Most importantly it allows you and your team freedom to choose the language they wish to work in.

History

16 Oct 2001 - updated for beta 2

License

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

About the Author

Chris Maunder

Founder
The Code Project
Canada Canada

Member

Follow on Twitter Follow on Twitter
Google+
Chris is the Co-founder, Administrator, Architect, Chief Editor and Shameless Hack who wrote and runs The Code Project. He's been programming since 1988 while pretending to be, in various guises, an astrophysicist, mathematician, physicist, hydrologist, geomorphologist, defence intelligence researcher and then, when all that got a bit rough on the nerves, a web developer. He is a Microsoft Visual C++ MVP both globally and for Canada locally.
 
His programming experience includes C/C++, C#, SQL, MFC, ASP, ASP.NET, and far, far too much FORTRAN. He has worked on PocketPCs, AIX mainframes, Sun workstations, and a CRAY YMP C90 behemoth but finds notebooks take up less desk space.
 
He dodges, he weaves, and he never gets enough sleep. He is kind to small animals.
 
Chris was born and bred in Australia but splits his time between Toronto and Melbourne, depending on the weather. For relaxation he is into road cycling, snowboarding, rock climbing, and storm chasing.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionConvert from Fortran double precisin PinmemberTrupti Mehta20:46 7 Oct '08  
Hi,
 
I have a Fortran program which I have to convert into Java originally. I have converted the code completely but can't get appropriate resutls. The code contains lot of arithmetic calculations using double precision data type of Fortran.
 
I believe the data types of C++ and Java are based on same whereas of Fortran double precision is based on IEEE756. I want to know how to convert these double precision calculations into C++ normally. For example:
double precision d1 = 0.3648564D0;   // D is equivalent to e/E
d1**2  // ** indicates exponent
DSIN(d1)  // sin of double precision
DCOS(d1)   //  cos of double precision
 
The above are my main concerns which I find very difficult to convert. I use sin & cos for DSIN & DCOS. But Fortran 77 deals somthing differntly with double precision. How to convert/translate that into our normal C++ application is what I am looking for.
 
If you cna provide the same for Java that would be a plus for me, otherwise I will use the code accordingly of C++ in my Java application.
 
Please help me out. Am stuck up very badly.
 
Thanks
 
Terry

GeneralFile not found exception PinmemberJV12:29 11 Nov '02  
GeneralRe: File not found exception PinmemberJain Mohit1:18 10 Mar '04  
GeneralRe: File not found exception PinmemberFredMizac6:58 29 Apr '04  
GeneralRe: File not found exception PinmemberAza21:06 21 Sep '04  
GeneralNice Job Chris PinmemberNick Parker17:07 30 Apr '02  
GeneralCross language interoperability PinmemberPaul Watson14:17 17 Oct '01  
GeneralRe: Cross language interoperability PinmemberAnonymous6:47 18 Oct '01  

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

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120604.1 | Last Updated 16 Oct 2001
Article Copyright 2001 by Chris Maunder
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid