Google Search

Google
 

Wednesday, July 23, 2008

Video: Wrapping Windows APIs with C++/CLI

Presenter:Mike Taulty

C++/CLI is a great technology for marrying existing C/C++ code with new .NET code. In this session we'll take a brief look at how we can wrap up a Windows API with C++/CLI in order to make use of it from C# code.

The following text is a software generated transcript of the video. Click on a minute link to jump to a location within the video


Minute 0

Oh and will consist on a nugget session is one in a series of short videos we spend 10 minutes or so looking how we can do things with visual studio and the net framework minus m told you I wouldn t developer and platform group in Microsoft and UK and in this session I wanted to take a look at how we can use C steel I in order to wrap up existing code whether that be your C code or your seat code or whether that be Microsoft API is in order to make that code accessible from net C steel I really sits on the boundary between traditional Win32 code and net code in that it has the full power of both platforms available to its extremely powerful tool so I want to present rarely can a trivial example here of how we taken API and I spent some time looking to the Windows SDK

Minute 1

Unsuitable API and they came up with the API that manages your display settings and display adapters for your monitors and you ve got installed in the system so it is API looks is that there s only two or three calls and we need to worry about what you can do is you can call enumerates display devices and there are a number of parameters you passive are fundamentally about a lull and whatever there was it will come back with a list of all the adapters on your machine to get back adapter one adapter to adapter three and so on and you keep calling this API and you ll cited past a number here to stay her father at week we ve got a long picket when that with all the adapters until after the one which goes returns ferry status is at a very simple API and actually you can call it again with a number where the number represents which one of these

Minute 2

Brief that you got back in case you re talking about is you can call it with some adapter number here and in that case will come back with a comeback with all the displays on that particular adapter and so on and then if you want to be able to manipulate the modes of display on an adapter is another ago according on display settings and you can give this the information about an adapter that you got from the previous API is here and if you do that than a sentimental comeback with device mode one per cent at 1020 4768 talks to make 7360 Hz were ever likely and device mode to and device mode three and so on and so forth so that s really the Windows API we got these even display devices even display devices called in a slightly different way and even display settings I want to wrap this up so they can call it more recently from icy sharp code now I could do this in siege

Minute 3

Up and its route he invoke and if I was just calling one sold to a GIS is very simple parameters that might be the way to go and you could certainly adopt that approach that these particular API is that you guys get more complicated and as you find yourself bringing in more and more and more constants from paedophiles in to see sharp redefining enumeration that you ve already got a new guide trials you start to think about C deal I is right that those kinds of API is reacted in more work in the wrapping his bringing stuff across from headers then you are really hoping to and at that price were C who I really comes into its thought that it can take a look and not writing all the code in the session and it isn t copying and pasting the session but how it would build something that would perhaps use these API to present them in a nice way to net programmer and so on and visited their survivors got make a new project value

Minute 4

Object and were going to go for a C project here seal Hungerford class library and a wooden modem working folder and will colour display library is okay that and straight away because much as close as that of a second but then the analytical and literacy sharper through want of Iraqis and Tesco do the same time and is adding to the solution and other projects will call this will have literacy sharper Consul application colours test harness was okay that and straight away and run driver reference to the C project from the test harness will reconstruct testing against straight away again possible evidence that this test harness start a project and if it is unequivocally property project to you consider using see a lot

Minute 5

Or were not trying to produce a verifiable seal code we just tried to produce a seal go to we can use the full power of C from this project not have to worry about type safety and verify ability is indeed there is such worried so let s get on with our C project starting point means it must not project is often stand in effects H Reich and define a standard includes my project son of using Windows you can just bet that I won t get very far without using strings and whilst I really like the classes that come with standard shown library I tend to tight deaths and stronger to the type that he will call the basic string bass ran wide characters use Unicode characters I cover a standard string as finance of using that type of art supplies now whether it s just my own experience and not I m not sure but I find in working with C in a live it s very easy

Minute 6

To go from a C notion that the string to a managed drink but I don t find it so easy to go the other way round and I generally have to bring in some kind of utility retain some of the ring in my own head of Arkle string utility that will add that to the project lump sum source files I ve done earlier he has gone through the senior son and I might string utility agency think the earth will take a look at that sustained utility H just essentially says we have a classical string utility and has a static method on it if you give it a managed drink it will give you back a standard string which is a basic strength of turn to mutuality with an imitation of and CPP file you can see that in here what we ve got strength white string were using

Minute 7

Ourselves a copy of the string on the global heat with a disability asking to turn that into a standard string we free what we allocated on a global heat and return the standard string and the yes we are probably copying the string around a little bit more than we need to I m not too worried about them copying of strings at this point of this particular am scenario does worry me too much with the dissidents much about that is that it is a little utility to go from a managed stream into a standard string from the sense of the standard seat runtime library at Civic until this point otherwise all is lost and so were good with string utility brought in and horses amnesty visual studio created a display library H frozen a display library at CBP are either thing I need is someone to am to meet that under the loudest again against the source files one at a treasure I can be built on the fine so in order to encounter is a PII of his

Minute 8

Class structure as that I would build a managed asphalt adapter it would have a number of display devices on it and it would have a number of display modes that you can look at a display mode is wanted to things like where its high eight frequency and pixel that something like that such letters that think about adding his classes into project was that the disclaimer that is a fairly simple class to play with so little about my C project now in the source files or display mode lets skydivers in this look at how we build manager classes with C so what we ve got here in display mode that age is really unexpected display library he is a class we know it s a net Vatican s arrest class and only done and here it is publicly made available some simple properties frequency bits per pixel width and height

Minute 9

Can see that these are read only properties relegated yet another set and the deposit was overridden to string together nice to string representation of the display mode I head and made the default constructor in turn will so I don t want the consumer of my application constructing display mode and has won a use display modes and ending on the hats outgunning fermented this a C file where you can see that what we do is we bring in the standardis out using generic collections are here as well and we bring in a standard paedophile and paedophile Khashoggi display mode we write a constructor we rightly get if of the different properties very simple as full back straightaway to internal and fields and on the other right to string with string format exactly the same way she wouldn t see sharp so that s our first class and without too written with manage C it was the seal

Minute 10

Aid on a classical display modem is a very very simple class so if we pop over to test harness and it is tidy of theis in here and Saunders threaded less code than straight away we can already go and pick up display library display mode has got load we could try and create one of those now just said that I shouldn t be allowed because we made the constructor internal to the assembly that would forget already getting a feeling for these things look like bits per pixel display frequency height rates to strengthen someone is already that is showing up in being available to us in our sea sharpeners coming from C Ally are getting so we said we also had a class called a display device at school and in existing code flat display device and this is again a very very simple class so in display device are always gone a device ultimately was ever there net class display device it has a name which

Minute 11

A read only property and that s it we have an internal field to the name so nothing rocket science Unicode hearing that we just include display device rewrite the constructor and rewrite the get of the name has just rebuilt so that I not only very an exciting display mode display device simple things now I figured that at some point I will partly want to throw an exception it from my C code back into the net world and I went ahead and if I m my own exception class others were allowed in that code to his the exception code was looking on a trial and you consider in fact in online than examples you are tended to put the definition of the class in the header file and then the implementation C file you don t have to do that with net

Minute 12

Indescribable implementation in the header file generally speaking I haven t really done that of the season examples of implementation this particular header so I done here is defined my own display exception to derive from application exception of a place to stand a construct as you d expect to see this essentially is a class that used to derive at all the exceptions I might have a throw from Sun Valley one bass glasses anyone consumes my library can just catch that particular type of exception and anything derive from it provides with 1 Convenient Place to catch things I think I only had a defining one subclass of this so if we are defining display change exception based on display exception and essentially and overthrow the system he tries to change the display mode of the machine and it fails so look at that codeveloper while but essentially you can see that in this case all of the code is pretty much in his header file we have the idea of the

Minute 13

The mode which was failed around a lot rather than mode which we failed to set on the display so you can pick up from the exception to store their private property and if you look at implementation files it was practically nothing going on in there in this particular case of all the code into the header file so it are an exception of us know that we can use and should some be failed to change the display mode and a base class of any kind of exceptions that we thrown project okay so little ahead and add in what is a slightly more meaty class again and again existing out of the project and it s the display adapter that score and throw in the definition and implementation of the ankles of the Windows does not look at this adapter class to go and look to adapt to the age so what is saying here is we have an adapter and adapter derives from display device at a name

Minute 14

And you can see that it has a number of different properties on it as the current displaying over the adapter that visual display mode and you can both get and set that display motor you can try and change the display mode and that might cause us to throw an exception you saw a second ago we consider which disclaimer is very set in the registry you can only get that don t allow you to change in this particular case we give you the name of the device as a managed drink with them USB adapter is removable is attached to the desktop is at the primary device carried of the GAA does have small modes that and other tropical it is a mirroring and drivers some kind of internal software mirroring of display devices died in relocating this detail here you can ask an adapter for its array of display devices and solicitor you all the devices attached to an adapter you can ask it for its display modes again this will give you the modes attached

Minute 15

An adapter note that were using a race who we could easily have used generic collections like this is I went ahead and R D adapters class I put a static property called all adapters so we don t originally around this idea of this in API where you called Enon display devices because that will adapt one adapted to adapter three from net perspective what I wanted to do was just built a walk up as their adapter all adapters and that would give me all the adapters that we knew about my fifth reach around them and so on and so forth so essentially this property here all adapters gives you an array of every adapter that we know about of how we construct it really allow you to get it we also will give you back the primary adapter to the adapters that can be quite a bit and so the competitive classes with only and

Minute 16

You can see that there is some internal bits and an pride at stake that were keeping around to make this work will come back into the second notice was again that the constructive adapter is private I don t want my consumers are going heading and creating adapters I want them to come to me and ask Fred act as the primary ways they can do that history has all adapters property and to this primary that property both of which are static okay so let s got into the implementation file for adapter you can see that we are bringing in pretty much all the other paedophiles are surely so far because we is all that stuff in here we have a simple fact the simplest construct you could have and they will regard it is this static property called all adapters that ultimately returns an array of our managed array of adapters and the way that this routine work to this is the first literally where we ve had some code that does both manage in a manage work

Minute 17

And even display devices and to the fails and felt when there are no more display devices we go around increment in this device number of stars zero sodium as the details of the Zero s device and a cigarette of it will increment that for the first second and third and this function fills in a structure for us of a particular type call display device this is an unmanaged I am function and structure so this comes from win duty either agency we initialise that structure just to clear it out we quarrel either on display devices if that succeeds it is recreated new adapter ring I have set the name the device name and the flags so each device comes with a bunch of flanks that tells us something about it and you can see here is creating manage strings from unmanaged strings to represent those things and amateurs put that adapter entry into list we renationalise the structure of

Minute 18

And the again such very simple as causing Windows code to build unmanaged generic list of manage structures that we defined in C using unmanaged data to populate if you read about this function here it is almost nothing or it doesn t taste that structure that has gone find it so takes that structure is zero as it has in excess one member to be the size of the structure which is a common pattern in Windows API is so that s how we go about getting all the adapters on a system that is that we make a note of the name of the adapter in its device name and some flags about at this lifestyle is quite a lot about the adapter so as you look at some of code you can see with a simple property access of the device strained if the display or is the adapter removable we can get by this checking the flanks with a particular value and we got lots of his flag access and so rather than exposing the flanks to the caller

Minute 19

Why chose to do was expose the simple bouillon properties and just go ahead and check these the caller so are we removable is it attached to the desktop is a primary device is if the GAA does have traditional modes is it a mirroring driver and etc etc etc never static property called primary adapter when you come to get this for us essentially what we do here is really rather wasteful we don t call the all adapters property and then reject each candidate to see if it s as if the primary device and if it is then that is what we return their note that we could have kept the primary device at the point were reconstructed all that actors and we chose not to do it here it will be a performance improvement to that supposed to keep going around asleep everytime you have a particular adapter weakened under all the devices attached to the adapter is display devices and we come back it with an array of

Minute 20

Low devices and we had to use the same API as he is very reused in on display devices but this time we give it the adapter name rather than passing in which is already before so to this method is the same as the one you saw previously and that you consider what we re doing here is calling this on a loop getting that some device details except this time these will not be adapted as they will be display devices so the only thing we take from them is their name and we added into the list that will building up and we go around with the same way to go before a fondling adventure series am using a standard strains of this is a basic string W chart T to represent the device name I get that from the name of this adapter by using my string utility that you saw it the other than that it s pretty much the same method as before except using the API to get display devices rather than adapters are other than that it s the same sort of things with Solomon

Minute 21

It ago worked without this file while you can see here another method for the current adapter get as all the display modes that it can support cellulite are using a different API but it turns out to work in a very similar way to the even display devices so again it is it a greater risk of display modes we have in our structure called a day of modes that we need to fill in we get hold of our current adapter name as a C friend and we repeatedly called Gina display settings for the adapter asking if all the modes that it supports an increment in this mode numbers with around the live so obviously give me the displays at his father s adapter frequently get we construct a new mode from the day of month so essentially this is and its class this as an honour

Minute 22

Its structure and is written function to go from the unmanaged structure to the manager class and get it onto the list we go round the loop again to take a look at this function that we ve written to go from and managed to manage see what that does so here we are giving unmanaged Surrey and unmanaged structure and coming back with a managed class is all we do is recreate one of these and we copy across the width to height the pixel depth and the frequency from unmanaged and managed to return the manager class was pretty simple plan to do that here so it other function than here we seen that function already has a function that will change the display mode services are set on a property called current display mode you give the display mode and it changes the current display mode you can see that what the dangers were going from this manage structure to the unmanaged day of my function to a

Minute 23

Showed you going one way this is going the other way and essential doing is taking this manage structure converting it into one of these and calling disc change display settings with that particular structure if that doesn t work with one exception saying that this didn t work so simple as that simple property accesses for the current display mode and the disclaimer from the registry and functions for initialising and going between managed to managed and managed to managed in terms of governments and as very much its that see the needs of the functionality that I wrote he is not very much to it if we don t build now because if we got some unresolved about linkages at the moment simple reason to valleys and it is visit my projects go to my link settings go ahead and add additional libraries in

Minute 24

In a specific move that dialogue particularly vital 90s and 32 live it is very functions native Scot had an okay that was four ahead and build the clean compilation so well that gunners go back to test harness and see what we can she do this code is that it is something useful but go ahead and display an adapter has been no stress that I m puzzled it is with all the adapters that we know about from all adapters to draw the adapters on machine in a safe reach adapter AA in adapters has gone right out some information about that some adapters right out perhaps its name something like that

Minute 25

And then for all of the display loads on that adapter is full mode but I done a load remember that we overrode to string them up mode closely very well in the first instance she can see all the different adapters in all the different modes I ve got here on this issue is already doing some some great work for is their extra press return on their lets write out more information about this and the adapter signal to get hold all fans is attached to desktop we can get hold of his primary device we can get hold of is removable and so on and so false riders things out we could easily get hold of primary and actor just by calling into adapter 5

Minute 26

Adapter not gives that specific primary adapter and so on and so forth so we made this and a reasonably easy to program these things from the sea shut by using C sale I do make those particular Windows API is which were to go back in and display devices and even display settings to make them a lot easier facility is writing Ramzi Sharp and hopefully get the idea that C Earlie it is pretty similar in terms of syntax to see shall and can do all of the managed work he wanted it and all of the unmanaged wether you want to do and specifically outfit this really was it the intention of what comes through from the session is that it really really powerful when it comes to making your existing code base in St C available to new code that you might be working a

Minute 27

On in Suchard or VB also one of the manage languages and it really hits that sweet spot of being able to take as we did here existing unmanaged code and wrapper it up in order to return managed entities practice in Suchard corridor or something like that so you can take advantage of the November 3 with presentation foundation and workflow you can take advantage of web services and all the other things you get in the net framework and mingle it really nicely with your existing Seal C code base just to try and summarise what was seen here we ve had a very quick and basic play with C Earlie and looked at how we could use it to wrap up Windows API is to make them more amenable to being used by sea sharp or VB code we saw we could easily build and manage types of C Earlie and were used unmanaged API is to populate data into that man is to return

Minute 28

To see sharp code it is ridiculous certain while she looked at some very simple Windows API is rapid and other little bit we didn t really look at some of complicated issues arising wrapping madness which is really around resource management and parcel of his comeback another and the subsequent sessions how to wrap up resources that need deterministic destruction from your C Earlie make sure the right thing happens on the manage side if you want to get more information on the C Earlie or Visual C in general then checkout as the end Microsoft com visual C if you ve got specific questions about this video then feel free to mail me my e mail address is there on the screen other than that thanks listening and hope to catch you on the subsequent

Click here to go to original video page

No comments: