Click to See Complete Forum and Search --> : Converting string to a true char * unmanaged array
clint878
April 28th, 2005, 03:48 PM
Hi,
I'm trying to use a library of old C++ functions that use the old-style (char *) strings. Unfortunately, I've spent 7 hours trying to convert a (System::String) to a (char *) with no success. There are plenty of functions out there that will convert from (System::String) to (_wchar_t []) but that type is equally troublesome to convert to (char *).
Anyone have any ideas on how to perform this transformation all the way, not just halfway to the (_wchar_t) type?
Thanks,
-Steve
dumbquestion
April 28th, 2005, 04:57 PM
String *stringstr = S"try this string...";
// To convert the String to char array
char* charstr = (char*)(System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(stringstr)).ToPointer();
// To cleanup the char array when you're done with it
System::Runtime::InteropServices::Marshal::FreeHGlobal(IntPtr((void*)charstr));
I think this is what you're looking to do. I had this same problem a while ago and found a couple of articles on the web about it. You can search "Marshal string .NET" and that will get you some more info about what I did above.
Good luck!
cilu
April 29th, 2005, 11:56 AM
See this article: http://support.microsoft.com/default.aspx?scid=kb;EN-US;311259
functor
May 2nd, 2005, 09:41 AM
I was trying to do the same thing. This is the function I have and it has worked perfectly for me so far. Basically i had to add an intermediate step and convert the string to a Char (capital C Char) array before converting it to a char array. :/ Anyway here it is:
void stringToCharArray(char resultString[], String *inputString)
{
Char inputChar[]; //Needed to hold String converted into Char temporarily
int i = 0; //Counter for loop
inputChar = inputString->ToCharArray(); //convert input String to Char array
while (i < inputChar->get_Length()) //Step through the Char array and convert to char array
{
*resultString = char(inputChar[i]);
i++;
++resultString;
}
*resultString = char('\0'); //add null character to the end of the string
} // end stringToCharArray Function
clint878
May 5th, 2005, 04:01 PM
Thanks! With your help, I now have two solutions that work perfectly.
Thanks again,
-Steve
Games are for Children
http://www.gamesareforchildren.com/
codeguru.com
Copyright WebMediaBrands Inc., All Rights Reserved.