Overview of Marshaling in C++
In mixed mode, you sometimes must marshal your data between native and managed types. Visual Studio 2008 introduced the marshaling library to help you marshal and convert data in a simple way. The marshaling library consists of a set of functions and a
marshal_context class that perform marshaling for common types. The library is defined in these headers in the include/msclr directory for your Visual Studio edition:
|marshal_atl.h||Functions for marshaling ATL types|
|marshal_cppstd.h||Functions for marshaling standard C++ types|
|marshal_windows.h||Functions for marshaling Windows types|
The default path for msclr folder is something like this depending on which edition you have and the build number:
C:\\Program Files (x86)\\Microsoft Visual Studio\\Preview\\Enterprise\\VC\\Tools\\MSVC\\14.15.26528\\include\\msclr
You can use the marshaling library with or without a marshal_context Class. Some conversions require a context. Other conversions can be implemented using the marshal_as function. The following table lists the current conversions supported, whether they require a context, and what marshal file you have to include:
|From type||To type||Marshal method||Include file|
|System::String^||const char *||marshal_context||marshal.h|
|const char *||System::String^||marshal_as||marshal.h|
|const wchar_t *||System::String^||marshal_as||marshal.h|
Marshaling requires a context only when you marshal from managed to native data types and the native type you are converting to does not have a destructor for automatic clean up. The marshaling context destroys the allocated native data type in its destructor. Therefore, conversions that require a context will be valid only until the context is deleted. To save any marshaled values, you must copy the values to your own variables.
If you have embedded
NULLs in your string, the result of marshaling the string is not guaranteed. The embedded
NULLs can cause the string to be truncated or they might be preserved.
This example shows how to include the msclr directory in an include header declaration:
The marshaling library is extensible so that you can add your own marshaling types. For more information about extending the marshaling library, see How to: Extend the Marshaling Library.
Send feedback about: