C++/CLI におけるマーシャリングの概要

混合モードでは、ネイティブ型とマネージド型の間でデータをマーシャリングすることが必要な場合があります。 マーシャリング ライブラリ は、単純な方法でデータをマーシャリングして変換できます。 マーシャリング ライブラリは、一連の関数と、共通の型のマーシャリングを実行する marshal_context クラスで構成されます。 ライブラリは、次のヘッダーで、お使いの Visual Studio エディションの include/msclr ディレクトリで定義されています。

ヘッダー 説明
marshal.h marshal_context クラスとコンテキストフリーのマーシャリング関数
marshal_atl.h ATL 型をマーシャリングする関数
marshal_cppstd.h 標準 C++ 型をマーシャリングする関数
marshal_windows.h Windows 型をマーシャリングする関数

msclr フォルダーの既定のパスは、使用しているエディションとビルド番号に応じて次のようなものです。

C:\\Program Files (x86)\\Microsoft Visual Studio\\Preview\\Enterprise\\VC\\Tools\\MSVC\\14.15.26528\\include\\msclr

マーシャリング ライブラリは、marshal_context Class ありでもなしでも使用できます。 一部の変換では、コンテキストが必要です。 他の変換は、marshal_as 関数を使用して実装できます。 次の表は、現在サポートされている変換と、コンテキストが必要かどうか、含める必要があるマーシャリング ファイルを示しています。

変換前の型 変換後の型 マーシャリング メソッド インクルード ファイル
System::String^ const char* marshal_context marshal.h
const char* System::String^ marshal_as marshal.h
char * System::String^ marshal_as marshal.h
System::String^ const wchar_t* marshal_context marshal.h
const wchar_t* System::String^ marshal_as marshal.h
wchar_t * System::String^ marshal_as marshal.h
System::IntPtr HANDLE marshal_as marshal_windows.h
HANDLE System::IntPtr marshal_as marshal_windows.h
System::String^ BSTR marshal_context marshal_windows.h
BSTR System::String^ marshal_as marshal.h
System::String^ bstr_t marshal_as marshal_windows.h
bstr_t System::String^ marshal_as marshal_windows.h
System::String^ std::string marshal_as marshal_cppstd.h
std::string System::String^ marshal_as marshal_cppstd.h
System::String^ std::wstring marshal_as marshal_cppstd.h
std::wstring System::String^ marshal_as marshal_cppstd.h
System::String^ CStringT<char> marshal_as marshal_atl.h
CStringT<char> System::String^ marshal_as marshal_atl.h
System::String^ CStringT<wchar_t> marshal_as marshal_atl.h
CStringT<wchar_t> System::String^ marshal_as marshal_atl.h
System::String^ CComBSTR marshal_as marshal_atl.h
CComBSTR System::String^ marshal_as marshal_atl.h

マーシャリングにコンテキストが必要なのは、マネージド データ型からネイティブ データ型にマーシャリングし、変換先のネイティブ型に自動クリーンアップ用のデストラクターがない場合のみです。 マーシャリング コンテキストは、デストラクターの中で割り当てられているネイティブ データ型を破棄します。 したがって、コンテキストを必要とする変換は、コンテキストが削除されるまでしか有効ではありません。 マーシャリングされた値を保存するには、独自の変数に値をコピーする必要があります。

Note

文字列に NULL が埋め込まれている場合、文字列のマーシャリング結果は保証されません。 埋め込まれた NULL により、文字列が切り詰められたり残されたりする場合があります。

次の例では、インクルード ヘッダー宣言で msclr ディレクトリをインクルードする方法を示しています。

#include "msclr\marshal_cppstd.h"

マーシャリング ライブラリは、独自のマーシャリング型を追加できるように拡張できます。 マーシャリング ライブラリの拡張の詳細については、「方法: マーシャリング ライブラリを拡張する」をご覧ください。

関連項目

C++ のサポート ライブラリ
方法: マーシャリング ライブラリを拡張する