Click to See Complete Forum and Search --> : Managed C++ String


deathscythe
January 30th, 2007, 12:36 PM
Hi,

I have a string in my managed c++ code, and in some my other unmanaged functions I am using char* as a strig format. What I would like to know is how I can convert the String class in .Net to a char* so I can pass a string as a parameter.

Any help will be appreciated.

Thanks

James2007
January 30th, 2007, 02:12 PM
System::String ^ strData = gcnew System::String(L"This is a test string.");

cli::array<wchar_t,1> ^ arChars = strData->ToCharArray();

const int nLength = arChars->Length;

char * pData = new char[nLength + 1];

for (int x = 0; x < nLength; ++x)
{
pData[x] = static_cast<char>(arChars[x]);
}

pData[nLength] = 0;

// Do whatever with pData

// Then free it

delete [] pData;

deathscythe
January 30th, 2007, 03:29 PM
Hi,

I couln't get that piece of code to work, I think it's because I am using VS2003, some help in that would be good.

Thanks

Zaccheus
January 30th, 2007, 04:02 PM
I would use one of the marshalling functions which .net provides.

http://msdn2.microsoft.com/en-us/library/system.runtime.interopservices.marshal.stringtohglobalansi.aspx

Converting from unicode (16bit) to ansi (8bit) characters involves some tricky special cases (range 0x80 .. 0x9F) which are best handled by the framework.

Here's the MSDN example in vs2003:


using namespace System;
using namespace System::Runtime::InteropServices;

int main()
{
// Create a managed string.
String* managedString = "Hello unmanaged world (from the managed world).";

// Marshal the managed string to unmanaged memory.
char* stringPointer = (char*) Marshal::StringToHGlobalAnsi(managedString ).ToPointer();

// *** START USING THE CHAR ARRAY ***

// ...

// *** FINISH USING THE CHAR ARRAY ***

// Always free the unmanaged string.
Marshal::FreeHGlobal(IntPtr(stringPointer));

return 0;
}

James2007
January 30th, 2007, 04:16 PM
Hi,

I couln't get that piece of code to work, I think it's because I am using VS2003, some help in that would be good.

Thanks

I'm sorry. I gave code that is from VS2005. Managed C++ in 2003 has different syntax than C++ CLI in 2005.