Click to See Complete Forum and Search --> : How can I convert System::String* to char *


DelboyDee
August 27th, 2003, 05:34 PM
Hi People,

I am writing a .NET wrapper for an old C++ API DLL. I have a function that inputs a char* for a name. My Problem is that my C++ .NET wrapper function passes a System.String* but I cannot convert this to a char*. See the following code.


long Coreco::SapManager::getServerByName(System::String* name, SapServer* Server)
{
_CORSERVER hServer;

char* strname = CopyString(name);
long ret = _CorManGetServerByName( strname , &hServer);
Server->SetServer( &hServer );
delete [] strname;
return ret;
}

char* Coreco::CopyString(System::String* srcstr)
{
char* strname = new char[srcstr->Length]; //*** This line Fails At runtime ***
for( int f=0;f<srcstr->Length;f++ ){
strname[f] = (char)srcstr->Chars[f];
}
return strname;
}


The line "char* strname = new char[srcstr->Length]; " fails at runtime saying that a nullreference exception occured!?!? basically new returned NULL (I think). Why?

Questions:

1) I have included libc.lib for the new operator implementation is this correct?

2) Am I going about this in the correct way or is there an easier way to convert from managed string types to char*?

Many Thanx,

Delboy

DelboyDee
August 28th, 2003, 06:26 AM
Ive Found out how to do it. Code is in bold.


using namespace System::Runtime::InteropServices;

long MyFunc (System::String* name)
{

IntPtr strptr = (Marshal::StringToHGlobalAnsi(name));
const char* str = (const char*)strptr.ToPointer();


long ret = _MyDllFunc( str );

Marshal::FreeHGlobal(strptr);
return ret;
}


Del

joltgbg
February 20th, 2007, 11:06 AM
Thank you!
Been searching for a solution for 90 minutes now