Deriving from C++ classes in C#

  • Thread starter Thread starter Urs Wigger
  • Start date Start date
U

Urs Wigger

I have a C++ class which I would like to use without changes in C#
applications. All the C++ class' definition is inline, i.e. the class
'library' just consists of a single header file. The class contains some
pure virtual functions. In a C# application I would now like to derive a
C# class from the C++ class and override the virtual functions.

Unfortunately I have not found a sample that is simple enough and
demonstrates the technique to do so. I succeeded with just calling C++
class methods from C#, but the tricky point is being able to derive a
class and override the virtual functions. I'm sure there must be a way.
Can anybody help me?

Thanks in advance
Urs

PS: For direct e-mail contact, please remove leading 'ns_' and trailing
'_ns' from e-mail address.
 
Hi Urs,

You will have to modify your class in order to make it managed one as C#
classes can be inherited only from classes declared in managed code. To do
so, you will need a brief tutorial on Managed C++ - there should be kind of
migration guide from C++ to Managed C++ in the MSDN at least and I think
there's a number of tutorials on the Internet.
 
Hi Dmitriy,

Thanks for the answer. I succeeded to make the C++ class managed, derive
a C# class from it and can now call methods of the base (C++) class from
a C# application. However, I still didn't succeed virtual functions
getting treated correctly. In fact, calling a method of my class always
results in calling a virtual function (of the C++ class). I would like
to override this virtual function in my C# application. How do I have to
implement a virtual function of the C++ base class in the __gc wrapper
so that my overridden function in the C# application will be called
instead of the (C++) base class' implementation (That's what always
happens). Do you know an article or sample that handles this topic ?

Best Regards
Urs
 
The overriding method should be declared with the "overrides" keyword (and
NOT "virtual" - the compiler will keep silent if you do so but this won't
work as you want it to).
 
Back
Top