Created
July 23, 2016 17:48
-
-
Save siliconbrain/5ee2d0133c9ec9dffac6b2a3630ac939 to your computer and use it in GitHub Desktop.
dump an object's memory to a stream encoded in hex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ios> | |
#include <ostream> | |
struct memory_dump_t | |
{ | |
typedef unsigned char byte; | |
byte const * const address; | |
std::size_t const length; | |
}; | |
template <typename T> | |
memory_dump_t dump(T const& obj) | |
{ | |
return { &obj, sizeof(T) }; | |
} | |
std::ostream& operator <<(std::ostream& stream, memory_dump_t const& mem_dump) | |
{ | |
auto original_flags = stream.flags(); | |
stream.setf(std::ios::hex, std::ios::basefield); | |
{ | |
auto stream_ = stream << std::setw(2) << std::setfill('0'); | |
for (auto ptr = mem_dump.address; ptr < mem_dump.address + mem_dump.length; ++ptr) | |
stream_ << &ptr; | |
} | |
stream.flags(original_flags); | |
return stream; | |
} | |
/* | |
Usage example: | |
MyObject foo; | |
// ... | |
std::cout << dump(foo) << std::endl; | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment