12.03.07
STL/CLR: 2008 C++/CLI的利器
C++/CLI 雖然算是ISO C++ 相容的一個語言
但是就EC++說的一樣 C++ 是一個語言聯邦
在STL中運作是需要共識的 也因為這樣 Managed Type 在 STL 沒有辦法 很正常的使用
VS2008中 C++/CLI 中加入了一個大利器 STL/CLR 這是一個 STL在CLR中的實作版本
他將所有的元件放在 命名空間 cliext 內 如 cliext :: vector
組件檔是 Microsoft.VisualC.STLCLR.dll
當然最重要的是 cliext 內的容器是可以容納 Managed Type 的
為了能讓原始碼可以誇越STL和cliext
我們可以使用下面的巨集
#define _STL_OR_CLIEXT std 或 #define _STL_OR_CLIEXT cliext
接下來使用 _STL_OR_CLIEXT::vector 就可以更改 _STL_OR_CLIEXT 的 來切換兩者 了
範例如下
#ifdef _M_CEE
#include <cliext\vector>
#define _STD_OR_CLIEXT cliext
#else
#include <vector>
#define _STD_OR_CLIEXT std
#endif
如同STL, 在cliext的容器 中運作是也是需要共識的
以下為想在cliext中運作的 Type (當然包含Managed Type ) 需要的共識
最重要的當然是和別的容器互相利用囉 (如果沒有 大家也不會用他吧)
需要互相利用的容器分成兩大類 一個是.NET Collection 一個是 STL Container
先談和 .NET Collection 的部分 : 這部分問題比較小 cliext 有可以接受.NET Collection 的建構函式 可以使用
或是利用cliext::collection_adapter 來進行轉換
逆向操作則是使用 cliext::make_collection
STL的部分 要使用VC2008的新功能 msclr::interop::marshal_as
支援的型態如下表
| From Type | To Type | Marshal method | Include file |
| System::String^ const char * char * System::String^ const wchar_t * wchar_t * System::IntPtr HANDLE System::String^ BSTR System::String^ bstr_t System::String^ std::string System::String^ std::wstring System::String^ CStringT<char> System::String^ CStringT<wchar_t> System::String^ CComBSTR |
const char * System::String^ System::String^ const wchar_t* System::String^ System::String^ HANDLE System::IntPtr BSTR System::String^ bstr_t System::String^ std::string System::String^ std::wstring System::String^ CStringT<char> System::String^ CStringT<wchar_t> System::String^ CComBSTR System::String^ |
marshal_context marshal_as marshal_as marshal_context marshal_as marshal_as marshal_as marshal_as marshal_context marshal_as marshal_as marshal_as marshal_as marshal_as marshal_as marshal_as marshal_as marshal_as marshal_as marshal_as marshal_as marshal_as |
marshal.h marshal.h marshal.h marshal.h marshal.h marshal.h marshal_windows.h marshal_windows.h marshal_windows.h marshal.h marshal_windows.h marshal_windows.h marshal_cppstd.h marshal_cppstd.h marshal_cppstd.h marshal_cppstd.h marshal_atl.h marshal_atl.h marshal_atl.h marshal_atl.h marshal_atl.h marshal_atl.h |
以下為所有的 cliext 元件列表
- adapter (STL/CLR)
- algorithm (STL/CLR)
- deque (STL/CLR)
- functional (STL/CLR)
- hash_map (STL/CLR)
- hash_multimap (STL/CLR)
- hash_multiset (STL/CLR)
- hash_set (STL/CLR)
- list (STL/CLR)
- map (STL/CLR)
- multimap (STL/CLR)
- multiset (STL/CLR)
- numeric (STL/CLR)
- priority_queue (STL/CLR)
- queue (STL/CLR)
- set (STL/CLR)
- stack (STL/CLR)
- utility (STL/CLR)
- vector (STL/CLR)