如何在WinRT中调用类似STL的Vector和Map

来源:互联网 发布:算法工程师要求 编辑:程序博客网 时间:2024/06/07 10:01

资料参考:
1. http://msdn.microsoft.com/zh-cn/library/windows/apps/hh710418.aspx
2. http://msdn.microsoft.com/zh-cn/library/windows/apps/hh441569.aspx

通常情况下,在对C++组件进行编码时,可使用常规 C++ 库和内置类型,但抽象二进制接口 (ABI) 边

界处的 C++ 库和内置类型除外,该处需与 JavaScript 进行双向数据传递。

只有 Windows 运行时类型可以跨 ABI 边界传递。
分析:所以你在WinRT 组件里面编写的程序,需要使用Windows运行时类型,就是带有尖冒号“^”,而

不是传统的C++值类型程序。

虽然你也可以使用C++内置类型(如int,double),但是编译器会在公共方法的参数和返回类型中自动

将其转换为相应的 Windows 运行时类型,如 int32、flot64 等。除非跨 ABI 传递类型,否则不会进

行此类转换。


1. C++内置类型、库类型、和Windows运行时类型的区别?
答:
C++内置类型:就是我们经常使用的int,double,float,bool等和C++语言相关的类型。
库类型:
Windows运行时类型:声明为public ref class 类名 sealed。“^”这个尖冒号的类型,称为可激活类

(又称为ref类)是可通过其他语言(如JavaScript)进行实例化的类,这个尖冒号告诉编译器将该类

创建为与Windows运行时兼容的类型,sealed关键字指定该类不可继承。

 


2. 如何使用类似STL的类型系统呢?
你需要明白2点:第一点是具体类型集合,第二点是类型实现的公共接口。
具体集合类型(如 Platform::Collections::Map 类 和 Platform::Collections::Vector 类)在

Platform::Collections 命名空间 中定义。

类型实现的公共接口在 Windows::Foundation::Collections 命名空间 (C++/CX) 中定义。

这里重点说的是如何使用WinRT中IVector类型。
在WinRT里面的Class1.h里面加上

#include <map>using namespace Platform;namespace WFC = Windows::Foundation::Collections;namespace WFM = Windows::Foundation::Metadata;[WFM::WebHostHidden]public ref class Person sealed{public: Person(String^ name); void AddPhoneNumber(String^ type, String^ number); property WFC::IMapView<String^, String^>^ PhoneNumbers {  WFC::IMapView<String^, String^>^ get(); }private: String^ m_name; std::map<String^, String^> m_numbers;};Person::Person(String^ name): m_name(name){}void Person::AddPhoneNumber(String^ type, String^ number){ m_numbers[type] = number;}IMapView< String^, String^>^ Person::PhoneNumbers::get(){ // Simple implementation.  return ref new MapView< String^, String^>(m_numbers);}


 

下一步在你的Blank App(XAML)的MainPage.xaml.cpp的构造函数里面你就可以这样调用上述类了,
如下:

Person^ p = ref new Person("Clark Kent");p->AddPhoneNumber("Home", "425-555-4567");p->AddPhoneNumber("Work", "206-555-9999");String^ workphone = p->PhoneNumbers->Lookup("Work");


 

你需要注意的是IMapView和MapView这2个在不同的命名空间定义的。
一个是接口,另一个是实现。

同理,你也该明白IVector和Vector等接口和实现的类了。