[C++]C++/CX 编程简述

来源:互联网 发布:手机水平仪软件 编辑:程序博客网 时间:2024/05/15 00:13

C++/CX 是windows运行时的C++语法。它是属于Native C++,不使用CLR也没有垃圾回收机制,与.Net平台下扩展的C++/CLR有本质的区别,虽然两者语法比较类似,但是这两者是完全不同的。C++/CX是基于Windows运行时而诞生的,它运行在Windows运行时上,比在.Net平台上的托管C++具有更高的效率。

Windows运行时中不支持标准C++的long型。

访问器

public ref class Prescription sealed{private:    Platform::String^ doctor;    int quantity;public:    property Platform::String^ Name;    property Platform::String^ Doctor    {        Platform::String^ get(){return doctor;}    }    property int Quantity    {        int get(){return quantity;}        void set(int value)        {            if(value < 0) {throw ref new Platform::InvalidArgumentException();}            quantity = value;        }    }}

委托

//定义public delegate Platform::String^ GetString(Platform::String^ str);//创建GetString^ func = ref new GetString([](Platform::String^ str){ return str; });//使用Platform::String^ str = GetString("123");

事件

public delegate void GetInt();public ref class EventTest{public:    event GetInt^ getInt;    void GetIntEvent()    {    }    void AddEvent()    {        getInt += ref new GetInt(this, &EventTest::GetIntEvent);    }    void InvokeEvent()    {        getInt();    }}

集合

在Windows运行时里面可以使用STL,但不能在对外接口和方法里面进行传递,所以在Windwos运行时中需要使用C++/CX语法的集合进行信息的传递。Windows运行时的集合在collection.h头文件中定义。

Windows运行时组件异步接口的封装

  • 引入头文件和命名空间:在C++/CX中,通过使用在ppltasks.h中的concurrency命名空间中定义的task类来使用异步方法。首先需要引入头文件“ppltasks.h”和命名空间“concurrency”。
  • Windows运行时提供了4中异步处理的接口方式。
    • Windows::Foundation::IAsyncAction:无返回值,无处理进度报告;
    • Windows::Foundation::IAsyncActionWithProgress<TProgress>:有返回值,无处理进度报告;
    • Windows::Foundation::IAsyncOperation<TResult>:有返回值,无处理进度报告;
    • Windows::Foundation::IAsyncOperationWithProgress<TResult, TProgress>:有返回值,有处理进度报告。
  • 使用create_async方法创建异步任务:Concurrency::create_async方法的参数是个Lambda表达式,也就是匿名指针。而create_async能根据Lambda表达式中的参数和返回值来决定4中接口中的一种作为返回类型。在Windows运行时内部使用的异步方法可以使用create_task方法来调用,但是这个不能作为Windows运行时的接口来提供。
  • 使用Concurrency::wait(n)阻塞任务。

使用标准C++

Windows运行时组件里面支持使用标准的C++编程,但只是内部支持,在对外调用的方法之中传递的参数必须要使用C++/CX语法类型。在Windows运行时里面使用标准C++的通常方法是传入C++/CX类型的参数,然后将C++/CX的类型转化为标准C++类型,再编写标准的C++的代码,最后将结果从标准C++转化为C++/CX的类型,作为返回值返回。

标准C++与C++/CX的类型自动转换
标准C++的布尔值、字符和数字基础类型会被自动转换为C++/CX对应的类型,无需再进行转换,可以直接进行赋值和使用。

标准C++与C++/CX的数组的互相转换
一般原则是避免在对数组元素执行大量操作的内部代码中使用该类型。

  • C++/CX数组转化为标准的C++数组
#include <vector>#include <collection.h>using namespace Platform;using namespace std;using namespace Platform::Collections;void ArrayConversions(const Array<int>^ arr){    //构建一个标准C++数组的两种方式    vector<int> v1(beign(arr), end(arr));    vector<int> v2(arr->begin(), arr->end());    //使用循环的方式构建数组    vector<int> v2;    for(int i:arr)    {        v2.push_back(i);    }}
  • 标准C++数组转化为C++/CX数组
Array<int>^ App::GetNums(){    int nums[] = {0,1,2,3,4};    return ref new Array<int>(num, 5);}

这里写图片描述

0 0