Convert managed type to unmanaged  
Author Message
Nikhil_Ribeiro_c7f6bf





PostPosted: Visual C++ General, Convert managed type to unmanaged Top

I'm using a copy of Visual Studio 2005 EE.

I need to use a String^ value returned by Directory::GetDirectoryRoot() with a third-party unmanaged library that accepts char *.

The compiler says that converting managed types to unmanaged type is not possible.

Any suggestions would be appreciated.



Visual C++6  
 
 
Mike Danes





PostPosted: Visual C++ General, Convert managed type to unmanaged Top

Couple of solutions:

MSDN How to article (works in any situation):

http://msdn2.microsoft.com/en-us/library/d1ae6tz5(vs.80).aspx

Using PInvoke in C++ (works if the unmanaged library is in a dll):

http://msdn2.microsoft.com/en-us/library/2x8kf7zx(VS.80).aspx

Another solution similar to the one in the MSDN How to but shorter:

using namespace System;

using namespace System::Runtime::InteropServices;

int foo(char *bar)

{

printf(bar);

return 0;

}

int main(array<System::String ^> ^args)

{

String ^s = L"Hello world";

IntPtr ptr = Marshal::StringToHGlobalAnsi(s);

foo((char *)ptr.ToPointer());

Marshal::FreeHGlobal(ptr);

return 0;

}