How to use Windows API all-purpose PVOID* structure

If you’re into modern Windows API c++ programming, it seems things have gotten just slightly easier. Naming conventions for classes, functions, structs, enums, etc. just aren’t as confusing anymore. I’m sure technical experts know how to move virtual memory around, which is essentially what programming and problem solving is, but if you’re just sitting down for some casual tinkering, it’s going to be a nightmare. You’re relying on the developers before you to name things intuitively.

So now Windows API documentation has been trying to promote using their generic PVOID struct more. It’s safer, maybe. It’s nothing special. It’s a generic struct to get a pointer to some data, any data. But you have to cast the data type yourself.

Here’s an example of how you can do something:

#include <windows.h>

void SomeFunction(PVOID *pv) {
  for (UINT32 p = 0; p < 1000; p++)
  {
    cout << ((UINT8 *)(pv))[p];
  }
}

void YourFunction() {
  PVOID *ptrToData = (PVOID *)malloc(1000 * sizeof(UINT8));
  for (UINT32 p = 0; p < 1000; p++)
  {
    ((UINT8 *)(ptrToData))[p] = (UINT8)0x00;
  }

  SomeFunction(ptrToData);

  //Free the cached bytes, otherwise will have a disasterous memory leak fast, so pay attention!
  operator delete(ptrToData);
}

What this does is create a buffer using malloc, which is local memory, and filling it with some unsigned 8-bit (aka 1 byte) integers. And then you can send the pointer ptrToData to a function that accepts it.

When you are directly accessing the data, you must cast the PVOID pointer into the data type pointer you're going to be dealing with. In this example, the data is of UINT8, so I'd need to cast the PVOID pointer into a UINT8 pointer.

And of course, after you are finish with the buffer, you need to delete it. Otherwise, say you are dealing with giant bitmaps and not keeping track of things, well, let's say your RAM is going to choke fast. That's what is called a memory leak, boys and girls.

Anyway, hope this helps in your Windows API c++ adventures!