Converting Between Native and Managed Types

Introduction

One of the most useful aspects of C++.NET is the ability to interface seamlessly with existing native code. To do this, you have to be able to convert between native memory and managed memory.

The garbage collector can be considered a seperate process that controls all memory in a .NET application and ensures that memory is released when it is no longer being used.

Because the memory in .NET is managed differently than in C++, you cannot access native memory using .NET safely, and you cannot safely access .NET memory in native C++.

To use managed memory in native code, you must copy the contents of the managed memory into native memory.

Equally, to use native memory in a .NET application, you must copy the contents of the native memory into managed memory.

There is an exception to this rule in the __pin keyword, which is covered later.

.NET Memory Conversion

Memory conversions are performed by use of the System::Runtime::InteropServices::Marshal::Copy method.

const int nLength     = 20;
BYTE *pbData          = new BYTE[nLength];
System::Byte abData[] = new System::Byte[nLength];

// unmanaged to managed
System::Runtime::InteropServices::Marshal::
        Copy(IntPtr((void *)pbData), abData, 0, nLength);

// managed to unmanaged
System::Runtime::InteropServices::Marshal::
        Copy(abData, 0, IntPtr((void *)pbData, nLength);

delete [] pbData;

The System::Runtime::InteropServices::Marshal::Copy class has various methods to copy managed to unmanaged memory and vice versa. See MSDN for more details.

The IntPtr class takes a void * pointer, and converts this to a managed pointer for .NET to use.

The __pin Keyword

Because .NET (garbage collected) memory is in effect controlled by a seperate process, it can change location at any time.

In C++.NET, the __pin keyword prevents the garbage collector from moving the memory until the pointer goes out of scope.

This gives native C++ the ability to directly access managed memory safely.

The above can therefore be alternatively performed the following way:

{
   const int nLength         = 20;
   BYTE *pbData              = new BYTE[nLength];
   System::Byte abData[]     = new System::Byte[nLength];
   BYTE __pin *pbManagedData = &(abData[0]);

   // from unmanaged to managed...
   ::memcpy(pbManagedData, pbData, nLength);

   // from managed to unmanaged...
   ::memcpy(pbData, pbManagedData, nLength);

    delete [] pbData;
}
// going out of scope releases the __pin

This is less efficient than the former method because it requires that the unmanaged 'memcpy' function be called from managed code.

Strings

Strings in .NET are held as unicode values, which are 2-byte characters.

Note: In non-UNICODE builds, the string is converted into 8-bit characters using the current system language's code page.

Managed to Native

String *psString = S"Hello";
__wchar_t __pin *wszString = ::PtrToStringChars(psString);

CString sString(wszString);    // uses the LPCWSTR constructor

Native to Managed

const CString sString = "Hello";
String *psString      = new String(sString);

This method uses the LPCWSTR constructor for String in UNICODE builds, and the LPCSTR constructor for String in non-unicode builds.

Conclusion

We have seen how to convert between managed and native memory, as well as how to convert strings from managed to native. These conversions are the backbone of being able to write your own wrappers so that .NET applications can use existing C++ code.

You can also use these conversions to interface with existing C++ libraries, or write your own interoperability wrapper for COM objects.



About the Author

David McClarnon

He first encountered Windows programming using Visual C++/MFC version 1.5 on Windows 3.11 a very long time ago. He is now a contract developer specialising in .NET/native interop with p/invoke.

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: December 18, 2014 The Internet of Things (IoT) incorporates physical devices into business processes using predictive analytics. While it relies heavily on existing Internet technologies, it differs by including physical devices, specialized protocols, physical analytics, and a unique partner network. To capture the real business value of IoT, the industry must move beyond customized projects to general patterns and platforms. Check out this webcast and join industry experts as …

  • The advent of compute accelerators, special purpose coprocessors that significantly improve the performance of traditional host-based central processing unit (CPU) computations, represents a major transition in the tools available to achieve supercomputing power. This white paper presents Dell solution offerings and shows how they push the envelope of available solutions that bring immediate added value to HPC users in terms of integration, flexibility, and efficiency of hybrid compute solutions.

Most Popular Programming Stories

More for Developers

RSS Feeds