Wednesday, February 25, 2009

Interop with char arrays

I'm doing a little managed app that calls unmanaged code. Turns out getting an actual char array to pass is a bit tricky, as the String.ToCharArray() gives you wchar_t. So here's the trick:

String * nameStr = Environment::MachineName;
char* name = (char*)(System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(nameStr)).ToPointer();
UnManagedMethod(name);
System::Runtime::InteropServices::Marshal::FreeHGlobal(IntPtr((void*)name));


Another asterisk to put next to "It Just Works."

No comments: