Effective C++/WinRT for UWP and Win32

>>All right, welcome to effective c plus plus 1rt. I’m brent, this is kenny, we’re going to be telling you all About this new language projection for the windows run Time a standard c plus plus language projection so diving into it. Basically we’re going to do two levels. I’m going to give you a High-level overview of the tooling, what it can do for you, How it will help you, makes development a lot easier and a Lot more efficient and then once you’ve got an overall viewpoint Of the whole process work flow kenny is going to dive deep and Show you the internals, show you how to be most efficient and What windows, the c plus plus language projection can do for you. So we’re going to have a high-level talk then we will Dive deep and answer your questions at the end. Let’s start off with what is a windows run time, we started off With code and it was great if you were running c++ but it’s a Flat cpi, i know back in the windows one days, the Documentation were 300apis and i knew the a’s, b’s, c’s and i Didn’t know the others at the end of the alphabet very well, And i could read through it, well, we don’t have Unicode,never mind, it was way back! I tried to come of with an estimate of what kind of windows Api surface we have, it’s rough, 600,000 to 1.2 Million, a lot of Apis, depends on how you count. That’s kind of unapproachable so We came up with a windows run time as an agnostic api for the System. It’s hierarchal and it’s a Classy model not a plat c style of programming model and the Nice thing about re time is it comes with meta data for the Apis. The metadata is powerful, it Gives us the ability to produce all the various language Projects so you can write programs in java script or c++ Or objective c or other language all targeting the windows run Time api. We still have 32 and everything That you know and like to varying degrees but we have this Great windows runtime api. So these language projection, The key phrase that we toss around internal is we want Programming in your favorite language to write windows Applications to be natural and familiar. So if there is an idiom that Your favorite language uses we want you to be able to use the Windows runtime apis using those idioms and what is natural and Familiar in one language may not be in another but with this meat Data without the apis and the windows runtime that let us Basically any programming language access them we can Expose those apis in gnarl and familiar way to you, now, c++ Are cptt which i can say more quickly, is a language — we Have another one that was an earlier projection for the c++ Folks and we will compare the two briefly and show you why we Think this is an improvement. So what is Cpp1rt? it’s a language projection for Wind dose runtime apis. It’s a header file library like Stl or boost. It also comes along with a tool That you can point it at a metadata file that describes a Windows runtime api and we will generate the library for that Api. So regardless of the language That somebody implemented a windows runtime control library Or utility library or whatever, you can get c++ header file Wrappers over those and access those apis naturally. So how do you get cpp1rt? Visual studio 15.7 Released today you download it and this Header file library comes with visual studio. It’s been in the rs4 beat at that previews up to now and you Might have actually tried it. What can you do with it? Well, basically every os api or any windows runtime api whether It’s an os or a third party to you is just a c++ class. You just enstantiate and call Members like you would any other c++ class. We go to great lengths to make it look, feel and behave just as If it were any c++ library. You will see what kenny does the Deep dive we go to great lengths to say you don’t have to learn a New type system. You don’t really need to know The windows runtime type system you can use w strings and Vectors and pass them into apis and it works. We do that in an efficient way. For most people they’re going to use the library to call apis to Use them, but if you want to implement windows runtime api The nice thing about implementing something as a Windows runtime class library is it’s accessible to anybody using Any language. A lot of people think how about Implementing it? you can implement it in standard C++ as well, too. So the nice thing — and i kind Of glossed by it, so i want to come back, is this is all Standard c++. If you’ve every seen C++ cx we had nonstandard key words, hat Pointers, ref classes, all this stuff that hurt my eyes to look At, especially the pointy hat things [chuckles] So here everything i’m going to talk about is standard c++. We test with the clang compiler, the microsoft compiler to make Sure we are just standard. That said we are very modern Standard c++, we’re c plugs plus 17 and we have features that We’re talking to the standardization committee in c++ 20 That we will will have rage if they get adopted so we’re Using modern standard c++ so you need a new compiler, we break Those all the time and get them fixed and use the features. We’re going to show you a preview of our zamle support, a Lot of people want to use that for their framework and we Talked to zaml to generate code files in our language projection. Previously it did c++ cx or c sharp now it does cpp1rt as Well. This is a preview. You may find bugs, the tooling is lagging a little bit behind Where i wish it was because i wish it was done yesterday like Every other project, but we’re going to plash it out, we want Your feedback and i’ll show you a completely working photo Editor app written in nothing but standard c++ using zaml. Let’s look at these three stages before we get to kenny’s part Where you will deep dive. Let’s say you want to write this Code, i want to fetch a web page and display it stay. I have a u i that references what i want to talk to i have an Ace http that will fetch it for Me and now i have to think b do i have to spin up a thread and How do i wait and do i block wait no gets put a dotget on the End and make it synchronous. This is what i like to write and Let me show you what we’ve been writing internally for the last eight years. That very first line translates to all this code. I have helper functions and macros here to simplify it. This is just creating a uri object. Constructing it with a string parameter, the next line the Http client is in another line of code and the third is waiting On a thread to finish, that’s probably five or six more pages of code. This is what up until now we’ve been writing internally at Windows when we want to do windows Runtime. We’ve not been evangelizing This, i don’t think it would having over too well if we had, This is windows runtime. We realized that was an activity Barrier to writing these so we created c++ cx. This is a number of years ago when c++ — sorry windows Runtime itself was new so we basically modeled very closely some concepts in the windows Runtime. We have these hat pointers. These are reference-counted objects so they’re smart Pointers but they know how to add ref and release. We have ref new, you have to allocate — it’s not really new I’m not happy allocating an object i’m going to you the Windows runtime and activating instances, the low level api but I’m basically activating a class and i need to tell cx that’s What i want to do so i have ref new, hat pointers. And if i want to do async work generally the way people use it Is with the patterns library, ppl. You can create a task, you can give it an lamda, the return Statement is lamda it spins one up from the thread pool and runs It on it. It has the thread pool thread Signal an event when you’re done, the main thread is Blocking on the event because of The .Get at the end. I wanted to get a web page, That’s all i wanted to do. I’m now using nonstandard data Types as well. I got this web page, i thought i Got a string but what the heck is this data function that i’m Calling? i need a char-a-star to pass to Print f. It turns out there is a Nonstandard property or technically a method on the Platform string hat that i got back from the function call and Then i go and throw some more stuff around, even main has some Types that i’ve never heard of before. It’s like i never actually wrote Much — i protested every time i had to, much cx code because i’m An old-fashioned c developer and c++ developer and I didn’t like this dialect. We came up with the idea let’s make a standard language Projection, one that’s pure standard c++ that can work Across multiple compilers. That was a challenge, we’ve been Working on it for two and a half years or so. I want to compare where we’re at now with where we came from with cx. This application, it’s not bad, about 80k bytes. But it has weird data types that i don’t understand. Let’s go back to the code you really wanted to write. You or i get a client, fetch the be page synchronously, i include Header files that are shipped as part of the windows sdk, they’re All in this folder, turns out there is a windows foundation.H That are the windows foundation come files and that’s a good Name because those are the types that are in the windows Foundation name space so we put them in a sub folder, you will Find about 220 name space header files in there. I need the windows webb http client so i include that header. I don’t like typing all that so i have a using name space. I’m using print f so i include stood io. When i get my page class back now it acts like it were a Standard c++ spring type. I can call c stir on it to get What i need to print f. When i wrap the thing with the Regular main it’s the regular main that you know and like, Considerably. [Chuckles] there’s one call that you have To make to make the windows runtime initialize. Cx did this for you because it knew you were using all these Weird main entry points it knew he wants to use the windows Runtime, we have a c++ class that does that for you and of Course the d structure will uninitialize at the end. That’s it. That is your standard c++ program bonus! When you compile it, we’re 23k bytes instead of 80. So in this case we’re 70 — let me not — it’s only 70 smaller! Than the cx version. To be fair, majority of that’s Because i don’t use ppl. The parallel patterns library is Template base classes, they produce a lot of overhead when You enstan retiate all the which Ises. If you shay a standard app and Change it to c++ you get about a 30 reduction in size. Conversely, i have taken another app that was all network Communications, all async operations, all ppl, like every Other line it seems like. I got the same 70 that you see here. We’re more efficient, we’re standard c++, two wins. Doesn’t taste good or smell great but, you know, what can i Do? everything i’ve shown you now You could do today with just our header files. All i did was pound include some header files and enshantiate the Classes. Notice the uri variable there, i Just allocated on the stack and then i call methods on it with a Dot. Comeback to this later but we Basically say use our classes as if they were the object itself, It’s not really, you’ll see shortly but as if it were the Object itself and call methods on it. Everything here is just in a header file library, there is No runtime that you need, just Include the file. However, we didn’t think that Was good enough. We wanted to help you build Great applications in a more efficient way so we wrote a Visual studio extension. Eventually this will ship as Part of vs itself but because of timing and we want to rev it Because it’s new and we have the zaml base preview content it’s Up on the visual studio marketplace, you will get a Pointer to that in a second. You get a vastly improved Debugging experience once you install this extension. I will show you that shortly. We also have a new project in Add new items projects so if you want to build a new one we have Templates to get you started. It’s not that hard — well, it’s Not that hard for those of us that have dealt with it every Day to get started manually but these templates make it really Easy and the zaml application integration so when you build it In the zaml we do a right c++ dialect and the code applications. How do you get this? two ways. You can go to marketplace.Visual studios “come and search for Cpp1rt and install it, you can go to tools and extensions and Updates and search for the same thing. We found — it’s weird, we published this friday and i was Going to keep it quiet, and we’ve had about 100 downloads a Day since friday and we haven’t even written a blog post. This is the first public disclosure and people found it Somehow, i don’t know. We’ve been getting critiques, Reviews, ranging from we found this bug to this is fantastic! This is great! i like both. I like the bug reports better than another way because it Helps us make it better. Once you install this, let me Show you what it will do for you. First, i need to define a term. All the types — well, “all” is too strong. Most of the times that you pound and include these header files That you use, like the url type the http client type are what we Call projected types, they’re not really the uri class, that’s Built into the operating system. When I enstantiate on the class, It’s really just a pointer object. As such it’s just one piece of state pointer to the real object And visual studio kindly shows you Exactly what it is. [Laughter] well, it’s got a field Called m under vri and points to a v Table and there is the address as if you wanted to know that. I didn’t find that as helpful as maybe you do and by the way you Get the same thing in cx so we’re not lagging there or in Raw c++ with the wrl code but once you install our extension, It knows that this is a projected type. It’s really just a smart pointer to something behind and remember I had that metadata? i had metadata about all the Types so my debugging extension now can show the uri object like This. I see all of its properties. I see its values. I’m really just looking at this Instance of a smart pointer and what the extension does is it Goes and looks at the metadata and sees what properties are Available and synthesizes a call to the proper get function and Then formats accordingly. So i think this is a win just For the visex alone, if it did nothing else, this is one of the Key features our people loved. So let me switch over to my demo Machine quick and i just want to show you the Templates and show this to you live. Basically when you say file, new project, and you go to windows Universal, these things at the bottom with the blue icons, These are the project templates, three of the four that we have Right now, a blank app, that’s a zaml application, it has one Button on it. We have the core app, this let Us you write direct x or game-like apps and then we have The console application and we also — which is not in uw p so It’s in windows desktop and then we have runtime component which Let us you implement a windows runtime type. I will talk about all of these. First i want to go through the Console app and walk you through the structure. This is the app you saw before. One key thing, which i have to Mention is the pch file. Now, we have a tool that reads The metadata and, again rates these classes. It’s a compiler and it’s in the sdk. P it runs as part of the build Process for some other usages but the system headers which Were generated by that as well, there are about 40 megabytes of Header, that’s why we have them in separate name space headers So you don’t have to pull in the whole 40 megabyte each time. For a little app like this pulling in the couple of Headers, which they will pull in their dependencies, probably Results in a 2 on 5 seconds in your build time but if you are Building a zaml application like one i will show you later you Pull in dozens of these headers and they pull in their Dependencies, it can add about 30 seconds to your build time. That’s the worst i’ve seen. I don’t want to do that every time. I do that in the pch, take that hit once and then my incremental Dev time is very fast, in fact the last few times i’ve tested It, incremental accounts are faster than they were in cx. Put all of your includes there. Let’s start this thing up. We took the break point, we look at the uri, there is my Debugging that you saw before, we hit f5 to go to the next one. And i have an exception. Because i have no internet connectivity. And i’m not going to take time to do that, but i was going to Show you the page. If you looked at the page type, You can find out that we have the debugger extension on that And i can see the text and invoke the visualizers since That’s an html page i can click on that visualizer and you get All the debugging you did before plus some that you can see here. Back to the slides. All right so we’ve talked about Using system windows runtime types, like http client or uri, What about ones that you get from third parties, maybe a Teller control or maybe a class library, 1rt class library from A third party like the win 2d library, that let us you do graphics. We support that, too. Basically once you add reference To a metadata file which is a 1md file the build system Installed recognizes that your project has a reference to a 1md File and runs the compiler to produce the header file library For the types in that 1md file. In fact, technically that’s all We did when we generated the ones in the sdk, we just ran it On the headers — kenny will talk about that more. Here is an example. This is a library that’s Available via new get. I can go to visual studio and Manage packages and install this thing and what happens? In my project i get a set of 1rt header files that are located in A similar structure to the system ones under that 1rt Directory, one for every name space in that library. How do i use them? i use them the same as any other c++ class. I include my header file, because we like long names in The windows runtime, and put in name space so i don’t have to Write so much and cp affect i did he claire an instance and Call methods on it, it’s just a c++ class, really. This is how easy it is to reduce windows runtime types. So high level, add a reference to a 1md and you get a c++ 1rt Projection of the tiptoes in that 1md, automatically Generated for you. So that’s what somebody else has Written, what about writing your own? the problem up till now when you Are writing a windows runtime type, there are class instances Involved, query interface, interfaces, a lot of calm, Low-level goo that you have to manage, not with us, not with our language projection. The work flow here is a little different. This is where we probably need To slow down and spend a little time. If you tell us what the windows runtime class should look like And we do that by writing idl, but want your father’s idl [laughter] Not my idl, whoops, brand new idl, 3.0, We didn’t even want to Call it 2.0. Idl3.0, Which is going to look similar to what you might have seen. Once you write this class description we generate Everything for you except the actual implementation of the functions. So if you add — you say this class has two properties a Method and three events, you will have to generate — well, You have to provide the implementation of the bodies of Those methods. All the boiler plate we do for You. So we will actually generate Basically source files. We will generate in a hidden Folder — let me slow down again, go back and look at the idl. I write the idl, we give you the implementation of the classes, It’s implemented with throw and not implemented and you fill out The body and you go i forgot to fill out the body i need to add Two methods, you go to your idl, add them again, we don’t want to Overwrite all your work and we’re paranoid about that so we Generate the skeletal file often in a sort of tucked-away Directory, it’s in the generated files sources folders so you can Go there and copy and paste. I’m going to show you this i Want to give you a high level. So it will never overwrite your Implementation opinion then we have a base class in the class Name.G boy h, that does all the class factory stuff, interfaces, Putting the right methods on the right interfaces, et cetera, all You implement are just a standard c++ class. So this is microsoft idl3.0. It has one of everything in it Just so i can show you no matter what you want to do it’s not Complicated. This is more complicated than Most you will write. But i have a delegate because i Want to define my own event. This is a photo object and let’s Say you have some ai that can do photo recognition on it and fire An event when it recognizes, it would be like the scott Recognizer if you saw the keynote this morning. So i have a delegate that describes the signature of the Handler and then i have this class photo. I’m going to use it in my zaml Application later although a slightly different version and i Wanted to find file property changed events. So there happens to be an interface that zaml uses for Property change notifications so notice windows Uizaml data identify property change, that’s All i have to say is this class needs to implement that Interface, you, by the way, will not write a line of code to Implement that, it’s all done in the base class for you. I want a couple of constructors. I have a read only property, That’s the one with just a getter. I have a read/write property, i could have wrote brackets get Colon set colon, but i don’t want to write extra characters. I have a method, midst are only async, based on the return time, If you want a future-like type they’re async, really. Then i have an event. Notice i have concepts in here That standard c++ doesn’t really have. Standard c++ doesn’t know what An event is. You can write a pattern that Does eventing, c++ doesn’t know about properties, read/right or Read only, they know methods that can return values but how Do i know that’s a property, per se. Then i have interfaces. So this is really the windows runtime description of the type. Now you could think about it quite a while and go, well, i Think this would map to this and my implementation — in my implementation. We do that for you. When you add an idl file to your Project, similar to when you added a win md, we ran a Compiler generated headers for you when you add this to a Project we run the compiler and, again rate an implementation for You, at least a skeletal implementation. So this is the skeletal implementation h file for that Windows runtime type description i wrote in idl3.0. It’s similar, except it’s in the implementation name Space. Notice Struck photo, struck public — sorry, struck photo Derives from photo t of photo. This is the Crtp where you type in the class type you are Driving. The base class is being driven From. Then we have the constructor, The adult, the one i said i have the image name property if you Recall that was read only so the property maps to a method that Takes no arguments and returns the property’s value. We have the cp intensity property, that was read/write, Notice we have a pair of overloaded methods here, the Getter, like before, has no arguments and returns the value Mrfrp the setter is a void method that takes the new value To be set. My method is just a method, Nothing new about that. Then an event turns out event Really needs two methods a register for the event and an Unregister method and they’re Trickier but we generate those for you. This is the .H file we generate for you and there is a .Cpp file That has implementation but i’m not showing them to you because They’re all one line, throw, not implemented. So this comes back to something i brought up before, when you Are using a windows runtime type it’s that smart pointer. The thing that implements the windows runtime type can be Written in any language, cp p p Is a great — cpp is a great language to write that in. I want point that out in the photo editor if we have time. Win rt photo editor, that’s my projected type, it’s really the Smart pointer. Consumers are going to use that. In my implementation code base i have the implementation type and The only real difference in the name is the name space has the Extra node of implementation in it. The reason i bring that up is when we look at an Implementation like a complete application like the photo Editor app in some parts of it i’m implementing the photo type And in other parts of the pages i’m consuming when i implemented And i’m using two classes that are basically called “photo” but They’re in different name spaces. Just good to be aware of that. Comes up rarely. Also, let’s say i have five Classes and i’m implementing in my class library, i would write My idl files, i would get five win md files and then when i Publish my library what do i give to consumers? A win md and a dll. I have to give them a metadata About the classes and the implementation. We help you with that as well. Automatically merge all the idl win mds into one for your Project. That way you shift to components And if you have one project that implements this class library You can add a project reference to it and consume it, because Remember when you add a project reference to this thing, you Will be effectively adding the win md to your project that Causes this in the client code to generate header files and now You can consume it just like it were a c++ class. All right. Now let’s talk about the last Thing before we dive deep. Creating applications using Standard c++. Specifically zaml applications. Now you’ve seen the work flow. When you are writing an Application you’re defining types, you’re creating a main Page type, a detail page type, maybe your data bind to go a Data model type, you’re implementing classes and we’ve Seen how to do that. The only difference is you have Zaml page and what the zaml page needs to do to do it’s code In and then the zaml page, so everything is the same here, the Zaml page is compiled to yet another base class. I don’t know how much you studied cx and how it works, but Zaml applications use partial classes so you wrote one partial Class, zaml generated a code behind partial class and the Compiler merged them into the final class. There is no such thing as a Partial class in standard c++. So what happens here is you have your implementation which is Going to look just the same as we saw for photo and there will Be two base classes the zaml page class and most of the time We don’t care, we often generate these files in a directory that You don’t look at most of the time, it just works. You’re going to worry about here is my functionality, i need to Implement these seven methods or whatever. Okay, so let’s say i have a zaml Main page .Zaml, notice this looks like what we saw before, i Have a struck main tabling that drives from the base class file, It does all the zaml stuff, the 1rt stuff and i implement the Constructor and the register and unregister. I didn’t have to do any Zaml-related stuff or windows runs time Windowsruns time runs time related stuff. I just needed to construct what i needed for my desired Behavior. So what i would like to do is Show you an app, i will walk you through a high level, not every Line of code but at a high level what the app Has done my machine went to sleep. Okay, so here is the photo editor app and i will show you The functionality before we look through the code but this is a Zaml app, i can click on a picture, i can tell it to fit The screen, click on the edit button and select an effects. These come from that 12 get Package that i talked about so i added a reference to that and How about the sepia effect, apply it, i Can change, remove All effect, i can do two or three effects at once. Anyway, this is basically — i will remove all the effects. This is the application. So it does all the natural Things that a nice ui — and i will point out now, i can Comeback to it later, we will show you — we are going to open Source — have open source — that’s not what i wanted [chuckles] I want this! we’re going to open source this. It should have been live today but there was a glitch. There is a url in the last slide that will show you how to Download all this code. There is want a single line of Nonstandard c++ here. First off i mentioned that it Uses the new get package so if i go to Project manage new get Packages, you will see them installed here. I added it here, it added microsoft canvas to the project. Now, when i built that app the first time, let’s show all Files, the stuff behind the curtain. All of these generated files are Generated for you. So there are a lot of them here Because i have basically three classes, i have the main page a Detail page and i have a photo data model class and then i have The zaml code behind and the 1rt code behind and all this is Generated for you and if we look up under 1rt here are the header Files from the graphics the win 2d package that we talked about And that let us me consume them as if their windows runtime Types using c++. They are windows runtime types. We will go to pch, remember i said put all these here because It takes about fifteen seconds on my laptop to compile, let’s Do that once, you don’t want to wait for that every time and Then it sub compiles on most changes after that. We will go to main page, .Idl. This is the main page, this is what zaml needed to know about My main page. It has to construct it, you’re Going to use it in mark-up zaml constructs it so i need a Constructor. I have a read only property Called “photos” zaml wants to data bind so that collection and That’s where it displays the photos that you saw on the page And then when you do a — click the back button, i didn’t call That out, it does it in animation, i have an async Method you can tell that from the return type that does the Animation when you hit the back button. The reason why i need those, if we go to the zaml page itself There is photo editor main page so that’s it is name of the Class it’s expecting, that’s what i declared in my idl file. Here is data binding so that method star connected animation For back navigation, zaml referenced it here, that’s why i Declared it in my idl. If we look at the actual main Tabling .H it’s got more stuff on it because it has to Represent all of those photos and everything it needs to do And use compositors, to it dmra them in the grid and that’s You’ves implementation details for your code. You didn’t really need to tell it to write that in the file Because zaml didn’t care about i do want to show you one last Thing. Let’s look for save, button on click. This is my new favorite method in this example. It does six asynchronous Operation in a row. First we show a file picker, What am i going to show for that, i have to wait for them to Dial up and wait for the user to answer, that’s asynchronous, Right here, collate, picker save, i would have had to create A task in ppl which sends up background thread, passes the Lamda .Function to run, and kenny is going to go into Collate in more detail so i’m not going to stress it here then Once i have the file i open it, and it’s going to take a long Time to open because i have to make a round trip, then i need a Bitmap encoder and i’ve got to load those — all that Infrastructure and then i have to take the current visual for The photo because maybe i edited it, i have to take the current Visual and i store that into a render target bitmap and that Takes a while and that’s async. Then basically i tell the Encoder to flush it to the file and then i basically in the last Line say i’m done making changes to this file so if it’s remote Send all changes to the remote system. For efficiency. So i have, what, six co lates There? it looks like procedural code to Me, i didn’t block my ui thread or anything, we don’t go into What collate does, but it makes it easy to deal with async Methods, collate just missed the update and most support it, it Will be officially c++ 20. While the windows runtime itself Our headers don’t use collate we make it so easy that almost Every application ends up using collate and this is how hard it is. With that i will switch off to kenny and he will go into the Details of what is cpp1rt, i tried to give you the high-level Project flavor now what do i want to write? Kentucky thanks, brent, very cool. — I want to show you where you Can get at this stuff yourselves, you shoulds be able To plug in directly yourself so i usually begin with the dev Prompt and up there you will see the x64, native tools command Prompt. From there you have 15.7 And the Windows sdk at your fingertips. All the tools you need are here. One is our visual plus plus compiler and you will notice That is includes in the program files, you will see x64 Underneath and the idea there is you will request Compilings and you will target x64 in this case And then we have the c++ 1rt compiler and it resides in its Own version folder and that is the windows sdk. We don’t ship a 64 version, it shows up in that path because That’s where all the 64-byte tools reside. That binary is stand-alone, Statically linked and you can take that, copy that on the Build machine, run it from whatever your tool of choice would be for building your Applications. As an example let’s look at this Example of code. I am calling windows api, that comes from the windows Foundation name space so back in the console that’s what you need And i’m saying limit output, i want c++, i want to target c++ 17 And i want to use windows ad-lib, this is all you need to Build your application today. As brent mentioned these are Headers only, use cl or clang and it works fine. One final thing he allude to do co-routines and you need to Add/to wait for now and hopefully c++ makes that Available generally. Back in the application we need To answer the question where does this header come from. Back at the console we can demistify that. You will notice the include files for the dev command prompt And right at the end you will see under the windows sdk Program files we include cpp1rt and within there is that folder That brent mentioned where you will find all the headers. The neat thing is you can run this yourself and, again rate Those headers, directly so even if you don’t have windows sdk Installed, let’s say you copied this on to your old build Server, you can run this in — sdk and physical find the latest Application and build the headers for that. You can target a specific version of the sdk or just the Custom of 1mds that you might have put on to that server. Having said that i want to focus on the code and show you what we Can do with c++ 1rt and show you a set of practical tips that you can take away. The first is a set of things about async, so the first thing We want to do is make async synchronous. One thing that was common in the windows 8 time frame is while we Have these apis, what if you don’t care about ui, you’re not Building a ui application and you get this silly error, so we Have get retrieve async, we’re building an application that Downloads the rsv feed. I just want to syndicate that Out, how do i get that out? we add the .Get method, it will Block the calling thread until results are available and make That available to the caller. If an exception occurs it will Throw it at that point as well. The corollary is what if you Want to have async be cooperative, you are building a Ui application, then this is problematic because this is Going to block the ui and you really don’t want that to Happen. This is the case where co Routines come in handy. The first thing you do is remove The trailing dot get and repan the co wait. When you have a co wait expression in a function it Turns it into a co routine. In order for it to work you need To choose a co routine type. This is the return type here. We have a set of co routine types and we will stitch this up For you so the compiler and the library c++ 1rt work together to Create this on your behalf. The result is you have a fully Formed implementation action in this case that you can then Return it. You can return this to a c sharp Application and they can await the result as well. There is one gotcha that most people that are new to co Routines tend to run into and i want to highlight that here and Make sure everyone is aware as we get started. There is one character in the slide out of place. That’s this reference over here. When you are writing a co Routine, you must recognize that there may be suspension points. Introduced by the co wait expression and that’s a point in Which the execution returns to the Cooler stack, and the solution there is to pass by Value or capture by value so if you’re use to lamdas by now you Want to make sure it’s not taken out of context and same story Here, pass by value for co routines. Highlight that one more time. We have a synchronous function, You don’t want to copy a vector, you will introduce a lot of Interlocked overhead behind the scenes but in that case you want This to be efficient, you can call dot get, you want to make Sure you pass by value and then you can use this and it works great. Those are your two scenarios to build that into your muscle Memory. Now i want to look at the things We have done to dramatically improve performance and the first is optimizing string input And they appear heavily in the windows api so let’s imagine we Have a single, called two upper and you can imagine what that Would do, returns the result. We might have an h string that We received from some other api and we want to pass that in and We should expect that to work and we might have a wide string And like brent mentioned, we want this to work and finally a String literal should work as well the problem is this one Won’t compile, they are allocated different ways and They cannot be copied without an allocation in between, therefore We don’t provide an implicit co instructor to make that work so We can add an excomplicit constructor there. The problem is now they are hidden copies. We want to make sure we get a copy so we introduce copies and They are not ideal and certainly this is one of the things we Have seen heavily in cx code the number of copies that are created internally that are not Helpful to your performance so what we have done in the Generated code and i want to stress this is in the generated Headers, we use a set of param types. All the input types where there is a significant benefit we provide special types that will Do the binding for you and optimize the areas so the param Knows the scope and the lifetime and understands how this should Work and works with the lateral and avoids the copies for you. The thing to remember is that the language projection, the Cpp1rt compiled will inject this where you need it you don’t have To add this to your own libraries, this is something the Projection does for you so you can make the calls in the natural way that you would Expect. Building on that we optimized For collection input so you can imagine in api it needs a collection of numbers. You can imagine what this guy would do, return the sum of These values and we would want to call out in a standard way You might have a vector that you received from the sum of the Api, that it is the 1rt vector or a stood vector, my favorite Container type, it should work. The list of values, it should Work, the trouble, again, is these two will not compile. Vector view is just an interface you need to provide Implementation somewhere so who is going to do that for you? In cx you would have to specifically say i want to do This and it will create one for you but that’s extra work. We have a param type which is optimized for collections. This will not only make the compiling but it will aon void The copies so it knows the scope of that so if you have a large Vector, you can make this call and the callee will get at that Data without a copy and make sure that it’s invalidated in Case it incorrectly takes it out of scope. Slight twist on that is async. We talked about it already and There is one gotcha here and this is so we can help you write The correct code by default. This thing takes a long time to Execute, you want to make it async and we have a version of This however we want to make sure all the bindings work Except that the vector should not compile in this case it’s Clearly local and you want to make sure that an async function Doesn’t reference variables because the odds of this failing Are extremely high and we make sure it’s one compile and the r Value version won’t work the r value will so it forces you to Copy the vector or to move it and transfer ownership into the Api. Efficiency first but as productive as we can possibly Make it. Getting work on the thread pools. Now i want to focus on implementation side of things. As we’ve seen it’s easy to call apis and make those calls and How hard is it to provide implementations? Like this example we’ve seen how easy it is to create a co Routine and async those interfaces but what if you want To get work done? i have an algorithm here and the Trouble about this is there is no suspension whatsoever and There is no be point at which the caller is going to be Executionable so the call is not blocked so what we need to do is Introduce a suspension point even if you’re not co waiting Some other operation you need to make sure that we return to the Caller and resume on the thread pool and that’s what the bes Does for you we have a set of helpers, specifically and they Work on the windows nt thread pool and this is low-level Windows api so it’s incredibly efficient at present. It’s straightforward within a function to immediately switch To the thread pool to get work done. One of the things that happens When you are working on a co routine is that you want to make Sure that you get — you may have to get on to the right Context when you are done with your thread pool work. That’s imagine a variant of that example. We have a co routine and we switch to the thread pool and we Want to update that and it slows an h result wrong thread exception. The solution is to capture the original context within which That co routine was called so for that we have one option as The apartment context and we can capture the apartment context That that call comes from and that happens to represent the Thread for an sda for a ui application. We can capture that, switch to the thread pool, do work on the Background and switch back to the calling context and that Ensures we are back on the ui thread and this operation to Interact with a zaml control because now we are guaranteed we Will be back on that thread. We switch two threads here and incredibly straightforward to Write this code. However with rs5, we can go Problem with the lag. In this example how do we know this is really the right thread for this text block? Let’s imagine this co routine was called from some other which Was switched to the background there is no guarantee this was Called in the right context. You might write your application And you know it’s from an event and it will just work but if you Don’t, if you’re writing a component and you have no idea We have a solution for that and that’s the — when we switch to The thread pool after that we can switch to a specific Dispatcher thread so co wait resume foreground it will use The method in the background and stitch that together for your co Routine and make it straightforward and simple and Gets you back on the appropriate ui thread for a multi view application. So that’s a lot about co routines. Let’s talk specifically about implementing interfaces. There we’re implementing interfaces but we’re doing a lot Of the hard work for you. In this case we might have some Arbitrary interface so we have istringable, that comes from the Windows name space, and it’s a two-string method which runs an H string and i can sues that but how hard would it be to Implement istringable? i’m going to switch back out of The projection and use wl, atl, whenever you used in the past And let’s have a look at what that looks like. So there’s struck my type on implementing something. Over here i declare the phases i would like to implement and i Can provide the implementation. So far this might look somewhat The same as what you would have in wl or some other application. In this case i want to implement istringable and i provide the Implementation and note that it has the exact same signature as The one that i called. The caller will call two string Expecting an h string result and in this case i’m implementing it In the same way. There is no virtual function, no H result, the h string is in the handle and it isn’t in a parameter, it’s the same as you Would call. This makes it intuitive to Implement this correctly. If you want to go and create one Of these, we need to call the make function template and that implementation and the Projection. So make will construct Implementation type on the heap and return the projected type. Running out of time so i will make this brief but we have a Set of implementation helpers make, make self, get self and Many others that will help to you bridge that gap for more Interesting scenarios and it’s all documented online now as Well. So here is another example. I want to add another interface, i add it, provide the Implementation and it simply works, that’s all there is to It. Behind the scenes we do a lot of Work, it’s added by default, so on. More interesting scenario is creating collections. In this example you see i want to add the vector, and there are No h results, no standard c++ it’s convenient but it’s a lot Of work. Stuff a stood vector, that’s a lot. You have seen we use the parameter bindings and we make This work for you but if you’re inside an implementation and you Don’t have the inclination to implement these yourself, you Have to implement all these things, we make it simple to get That done for you. We have a set of helper Functions and here is an example of a single-threaded vector. This creates a general purpose implementation and returns an Ivector interface and you can see the projected type there and We can use that, pin members, iterate over them, this is a 1rt Type and you get to use it as any other type that you would Have received from api. If you need an ivector view you Can call the method and it will get it to you so a simple way of Getting that done for most scenarios where you need to pass Scenarios into an application or get data out of an api to an Application. Here is another example that Helps reinforce the value here. You may want to avoid the Overhead of populating that interface across the abi so you Can start off with a stood vector and move the contents of That into the implementation and that will work as you expect. We provide a single-threaded vector there is a container Version and observable versions as well. All of those are called single-threaded in the sense They don’t provide any concurrency, they’re not thread safe. So these are really great if you’re processing data one way Or the other across the abi and they get the job done for most Of the scenarios. They’re single threaded. 5Sdk was released today, you can do far more powerful things, if You need to add concurrenty or type strings, you can do that as Well. As we wrap up i want to talk About creating delegates in events. So drating a delegate, it maps To something along the lines of a function, it’s a callable or Invokable type. So we make it straightforward to Implement those without having to go and implement in an Interface so we might initially construct one, an empty one and We can initial eyes or assign a value using an lamda as in this Function or a free function or formal function you can check For validity or invoke the delegate as you would expect to do. So it’s straightforward in the amount of code that you need to Write to get this done. So the main scenario that you Want to use delegates for in the windows runtime is for events. Let me show you how that works. We might have implementation and I’m going to pick on a single-threaded observable Vector function which runs an implementation, it happens to Have an event called vector changed, that event accepts a Vector changed event handler that’s the delicate type and It’s generic so traditionally with c++ you would have to write Vector change event handler and then provide the lamda, so all You need to do now is add the lamda and we will construct is Behind the scenes for you and when you call the pen method we Will he voc that handler. One twist on that is if you want To deal with revoking the handler. A simple example is to retrieve the result of the vector changed Overload and capture that as a 64-byte token. We can invoke the handler by calling a pin, we can manually Revoke the handler, it takes the token, passes it back into the Ooechlt source and removes if from the internal array that the Api may have implemented. Finally the handler is now not Recalled because we have revoked it. We have one final tip here for You regarding events which is to use the order revoke key word. The idea here is that it tells the projection to call an order Revoker, what is returned is no longer that 64-byte value but is Instead an object that holds a weak reference to the event itself. If the vector itself goes out of scope, the handler will Automatically — will automatically deal with that. So, for example, when you want To revoke this manually you can call a revoke method and that Will attempt to resolve the issue, and if it still exists, somebody else has a strong Reference to that object, it will be able to revoke it for You. Naturally it’s an instructor, it Will revoke that in your class member or have it destroyed Automatically. In any case it’s conscious that It’s handling a weak reference and that’s handy, if you need to Solve that problem within your application, and this is a Convenient solution for more complex scenarios. Two more points, implementing your own events. So let’s say you want to implement that iobservable Vector interface, you don’t want to use a built-in function, how Do you implement the vector-changed event. You can use the event class template, provide the delicate Type and then you can call the add and remove methods to add The handler to the array and remove that handler from the array. This does all the work behind the scenes for you, it’s Concurrency safe, thread safe and it’s very efficient. You don’t have to implement the overload for the order Resoaker, that’s taken care of for you by The projection. This makes it simple. The reason this isn’t baked in is you can imagine Implementation with 100 events. You may not want to use this Implementation, you may want to use a sparse implementation, and You’re tree free to do that yourself by implementing the Overloads in whatever way makes sense for the application. Final tip with c++ cx, one of the things that developers did a Lot which they were supposedly not going to do, was use c++ cx Throughout the application. They were supposed to use it on The boundaries and it was too convenient to use it everywhere Else and a lot of developers used it throughout the Application internally for communication. So to make that scenario straightforward in terms of Porting your code, we provide a delicate, a variable delicate Which will work with 1rt types as well so you can use a stood String or whatever else you like and you can add and remove Handlers and invoke events just as you would with cx now with C++ but this is only for internals, just a helper to make Your lives easier as you port your applications from cx but it Is handy and useful. Brent? [Applause]>>brent: so you’ve seen it now I should add that we are using it a lot internally. Most of our windows runtime apis are written that way today and Everybody that can make the business case for it are Rewriting in this, our as far as device drivers are using this, We have an rs533d lls are now using cpp1rt. As fast as people are moving, they’re moving to this. We find out with the wrl there is 100-to-1 line of code of Reduction, and we found bugs because it’s more not Understandable, we really want you to use it. We want your feedback. So if you go to a visual studio And report a problem we will get the notification. If you have a feature request, let us know. You can also go to stack overflow and ask questions like How to. It’s not a bug or suggestion but I want to know how i should do that. We look at our request tag that way, as well. There are more resources here, Visual studio and the sdk i talked about the extension i Talked about, the photo editor app does nearly all the stuff we Talked about today and it’s been reviewed over and over by our Team as a guide for best practices. That url is not live last i checked this morning and it will Be in the next couple of days. It should take you to a landing Page and tell the editor is live. We’re going to put the source code up on github. Documentation has been updated For us. Basically you can go online and If you go to www.Microsoft.Com you can get You. With that i will close. Please use , this, help us find The bugs and we appreciate you coming. End end [end of presentation]

Tags: , , , , , ,


  • André Köhler says:

    Great, now the C++ experience for writing a WinRT app looks almost as easy as with C#.

  • Bartman Abyss says:

    Please upload 1080p in the future if possible. 720p is a bit soft when it comes to reading the code in the demos.

  • DigitalKingyo says:

    Photo Editor Sample is not yet available?

  • John Schroedl says:

    Photo Editor sample is up: https://docs.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/photo-editor-sample

  • LUDIJAK says:

    Great job Microsoft!

  • JaskanFactor says:

    folks need to stop using Auto and Lamda in sample code, if the point of the sample is to help understand a concept.
    As for Auto, it should only be used in code no else will ever have to read but you, cause the old way have having double info on type in an expression was working just fine. Now Auto on the left means you need to dig out documentation to findout what type was returned, in sample code only a maniac will do that.

    Lambda and auto and var in c# should all be removed. They help you type faster code thats much harder to maintain, cause its code that is harder to understand, bad for business , fun for hobby.

    They should create a programmer hobbyist version of the standards where lamda auto and var can live.

    There is nothing wrong with having function definition and declaration it makes it easier to read, no need for lamda, especially not in sample code, unless youre trying to reach only those are familiar with lamda syntax, if you can explain why you would want to use niche syntax when you trying to reach as many as possible.

    In Programming you want to maximize opportunity for reader of your code to understand what is going on, not have them reaching for API documentation every time they reach an Auto f***ing var, add a lamda to such an expression and you know the standards is now just for fun.

    Stop sticking lamda and auto in sample code, its not a game.

    How is anybody gona understand your sample code with auto all over the place, its like giving a speech where there are paragraphs where you take the 5th amendment.

    Lets get real folks, people have to do this for a living and all this auto lamda Bs is gona cause a lot of hassle down the road. Especially not in code your using to explain a new idea, unless your new idea is Auto.

  • John Kang says:

    Jesus christ. Does anyone remember original Windows Store App used windows runtime and it was called WinRT? So back then C++cx was somewhat equivalent to WinRT. Now there is C++WinRT?

    That's not gonna cause any confusion, seriously.

  • Alkeryn says:

    FFS that's damn annoying, can't you just let the users download the headers file so we can import them with mingw and compile on linux ?…

Leave a Reply

Your email address will not be published. Required fields are marked *