tags:

views:

237

answers:

3

I'm using a small C webserver. I'm doing some of the actual request processing with C# libraries.

I'm using a glue layer which appears to be written in something close to c++ to join the two worlds. It provides a 'public ref class' which I can derive from in the C# world.

If I want to derive several different classes from this in C#, how do I create instances of these derived classes from the C/C++?

What information (the class name? A factory function?) shoud I pass (and and in what form) from the C# to the C/C++ code?

I would like a solution compatible with .NET 2.0, and I'm using Visual Studio 2008 to create my code.

+1  A: 

See How to call a managed DLL from native Visual C++ code in Visual Studio.NET or in Visual Studio 2005.

http://support.microsoft.com/kb/828736

billb
the linked article makes no mention of creating objects on the managed heap from unmanaged code.
John McAleely
This line creates the object: // Create the interface pointer.ICalculatorPtr pICalc(__uuidof(ManagedClass));
Eddie Deyo
ah, fair enough
John McAleely
+1  A: 

Use the #using directive to import your C# assembly into the C++ code.

#using "ThingLib.dll"
using namespace ThingLib;

If you only want the C++ code to be aware of the base class, you'll need to call some kind of factory method.

ThingBase^ thing = myThingFactory.MakeThing(aParameter);

If you want to actually instantiate the derived classes in C++, use the gcnew operator.

ThingBase^ thing = gcnew DerivedThing(aParameter);

There's a good summary here of the new C++ language features for talking to managed code: http://msdn.microsoft.com/en-us/library/xey702bw.aspx

Eddie Deyo
how does 'DerivedThing' (declared in a .cs file) become visible to the C++ code?
John McAleely
I suppose that's useful information ;) Use #using. I added an example.
Eddie Deyo
+2  A: 

I have realized several times that people are sometimes not completely aware of the difference between managed and unmanaged code, so I would just like to summarize:

  1. You cannot simply call managed code from a native C++ application. In order to call it, you will first have to expose your .Net code to COM, and then instantiate a COM object in C++. This way your native app thinks it is creating a COM object like any other, and .Net is doing all the interop in runtime.

  2. Second way is to use managed C++/CLI (which is not native C++, but supports both worlds). This way both C++ and C# apps are managed and can communicate seamlessly. So as long as the "glue layer" is written using managed C++/CLI, you can both work with native and managed data.

As your originally mentioned unmanaged C++, then the answer would be to go for 1st solution: expose the managed object to the native world through COM interop. If you don't mind using managed C++/CLI, then you have a simpler solution - you can instantiate managed classes easily (with some changes in syntax you should quickly get used to).

Groo