Sample of Unmanaged C++ code calling Managed C++

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Does anyone have a simple "Hello World" like application that demonstrates
unmanaged C++ calling managed C++ developed in VS2005? I'm confused by many
posts as they discuss managed extensions from VS2003, and related techniques.
I have found managed to unmanaged technique very easy in VS2005, but have
not been able to build anything with unmanaged to managed calls. I have
legacy (unmanaged C++) that would like to leverage the .NET framework; I'd
like to build a managed utility DLL that my unmanaged code can call. How
about this approach?
 
MC-Advantica said:
Does anyone have a simple "Hello World" like application that demonstrates
unmanaged C++ calling managed C++ developed in VS2005? I'm confused by
many
posts as they discuss managed extensions from VS2003, and related
techniques.
I have found managed to unmanaged technique very easy in VS2005, but have
not been able to build anything with unmanaged to managed calls. I have
legacy (unmanaged C++) that would like to leverage the .NET framework; I'd
like to build a managed utility DLL that my unmanaged code can call. How
about this approach?

The approach may be fine. But as always, the devil is in the details. You
don't say what you have tried and how it failed.

I just built this trivial unmanaged toy application

//-------------------------------------------------------------------------
#include <stdlib.h>
#include <iostream>

__declspec(dllimport) void Square(int);

int main(int argc, char **argv)
{
int n;
char *p;
bool ok;

ok = false;

if ( argc == 2 )
{
n = strtoul(argv[1], &p, 10);
if ( *p <= ' ' )
ok = true;
}

if ( ok )
Square(n);

else
std::cout << "Bad command line";

return 0;
}

And this managed toy DLL

//-------------------------------------------------------------------------
#using <mscorlib.dll>

#pragma managed

void DoIt(int n)
{
System::Console::WriteLine("The square of {0} is {1}", n, n * n);
}

#pragma unmanaged

void Square(int n)
{
DoIt(n);
}

It works as expected. I built it wthe VS2005 but cleverly <g> I avoided any
issues related to MC++ or C++/CLI. Even more cleverly, I didn't try to pass
much ( a 32 bit integer ) in the way of parameters over the fence dividing
the two envirionments.

In other words, my sample demonstrates a simple transition into managed
code. In the real world, things get complicated in a hurry. If you post some
details as to what you need to do you may get some suggestions from someone
here who has been there.

Regards,
Will
 
Back
Top