I think these functions should be a good starting point:
And to actually save this to a file, the function you have posted earlier is not good at all. Say you use the above to get a pointer (ptr) and a size in bytes (size), then you save with:
std::ofstream file;
file.open("myfile.dll",ios::out | ios::binary);
file.write((char*)ptr, size);
file.close();