Converting Between MFC/C++ and .NET Types

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Welcome to this week’s installment of .NET Tips & Techniques! Each week, award-winning Architect and Lead Programmer Tom Archer from the Archer Consulting Group demonstrates how to perform a practical .NET programming task using either C# or Managed C++ Extensions.

Many .NET methods are very picky about the types that you can pass as parameters. For example, the sockets, cryptography, and several of the streaming methods require byte arrays, which you must first convert from CString objects or C++ types. In addition, despite the fact that IJW alleviates many conversion issues, several situations still require you to manually convert a .NET type to a C++ type. As a result, converting between types is frequently a sticking point for coders new to mixing MFC and .NET.

This article illustrates some basic conversion code that should help you if you find yourself about to throw your monitor against the wall after the latest “can’t convert x to y” compiler error message!

Converting CString objects to a .NET Byte array

CString str = _T("CString to be converted to a byte array");
Byte barr[] = new Byte[str.GetLength()];
for(int i   = 0; i < str.GetLength(); i++)
   barr[i]  = static_cast<Byte>(str [i]);

Converting String objects to a C++ char array

#include <vcclr.h>    // Needed for the PtrToStringChars function
//...
String* s = S"String to be converted to a char array";
const __wchar_t __pin * str = PtrToStringChars(s);

Converting String objects to a .NET Byte array

String* str = S"String to be converted to a byte array";
Byte barr[] = new Byte[str->Length];
for(int i=0; i<str->Length; i++)
   barr[i] = static_cast<Byte>(str->ToCharArray()[i]);

Converting Int32 objects to a managed char array

Int32 myInt = 42;
unsigned char myArray __gc[] = BitConverter::GetBytes(myInt);

Got More?

This is by no means meant to be a complete compilation of all conversions between MFC/C++ and .NET. However, it will handle the majority of the cases you face. If you would like to add a conversion, just drop me a line. If I add it to the article, I’ll, of course, give you credit for the input.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read