Windows Assessment Numbers and a Lesson on Avoiding Unsafe Code
Windows assessment numbers are expected to be very useful for comparing computers in the store or for identifying performance bottlenecks in systems you already own. Other possible uses include altering an application's behavior depending on the system's capabilities. Of course, to leverage this you need to know how to use the APIs.
Working from the WinSAT reference, Bart De Smet developed a C# based application that demonstrates how to expose the assessment numbers to managed code. While it wasn't stated in the article, the use of unsafe code blocks suggests that it could not be implemented in VB.
Cory Smith took issue with what he considered unnecessary use of unsafe code, as well as other design flaws, so he rewrote it using Visual Basic. In his article about the process, he shows us how to deal with raw pointers without having to resort to unsafe code blocks.
Let’s delve into the work that was necessary to retrieve the generated image. Obviously this COM library was designed to be utilized by Windows Vista. As such, it was not necessarily designed to be used from your application or from .NET directly (and I am a little disappointed since the party line I’ve been hearing has been “all new API’s would be .NET friendly”).
As such, we have to do a little work to get this information. If we were using C++, it’s a simple matter of dealing with pointers. If we were using C#, we could utilize “unsafe” code to, again, deal with pointers. (Personally, I think the utilization of “unsafe” if there is an alternative is a bad idea, but that is a personal opinion so digest accordingly.) So how do we pull off the same functionality in this case without the use of “pointers”? Well, a pointer is simply an address to a memory location that contains the information we are looking for. .NET does contain such a construct to hold these and it’s called System.IntPtr. However, we can’t just simply pass an IntPtr to the method since it’s actually a pointer to a pointer. So, what we need to do is pass to the method a pointer to a block of memory that we can then use to pull the written pointer that ultimately points to the dynamically generated image.
This is where we take advantage of some of the interop features with a little help from the garbage collector. We first create a four byte buffer to hold a signed integer value (the real pointer to the generated image). This buffer is then “pinned” using the garbage collector classes. By pinning the buffer, it will tell the garbage collector not to move it around during GC compaction. We can then get the address to this location using the AddrOfPinnedObject. This will act as our pointer to the pointer in the get_Bitmap call.
These examples, as well as the underlying API, only run on Windows Vista.
Anatole Tresch Mar 03, 2015