So here's a fun task: how to use templates to do strongly-typed detour-style hooks without preprocessor magic.
(Totally off topic, so if y'all wanna flame or delete, feel free.)
Was working on this last night; I know others have invented this wheel but I'm super rusty in C++ (was always more comfortable in C, to my detriment) and was working on it at like 3am last night. Decided that for a rusty C++ programmer trying to "correctly" (elegantly, usefully) write template classes with a factory object and a "manager" (something to roll all the hooks together and patch/unpatch them all at once, as well as exposing the "real" function -- which varies depending upon whether a hook is installed or not, and has to be strongly typed) ... at 3am, was not wise.
something like...
Code:
void __stdcall MyFunc(int someparm);
template <class T>
class APIHook
{
public:
T GetRealFunction();
bool Hook();
void UnHook(); // probably should be bool, but failing to unhook is usu. fatal
APIHook(std::string libName, std::string apiName, T& hookFunc);
};
APIHook<void (__stdcall *)(int)> myHook("SomeLibrary", "ZwSomeFunction", MyFunc);
(Excuse any obvious syntax errors; I'm at work and my Eclipse C++ plugin is currently borked.)
The prob with this is that I'd like to avoid the template syntax in the object construction. I know this isn't legal code, but it would be cool if I could do something like:
Code:
APIHook myHook("SomeLibrary", "ZwSomeFunction", MyFunc);
I know this isn't valid (compiler doesn't have a non-specialized APIHook type), but it would make the syntax WAY less cumbersome. Aside from the syntax error, all the info the compiler needs is there (the function pointer type can be inferred from the passed-in detour method, etc.)
Thing is, I'd really like to avoid doing this with a macro (I probably could make it work with the preprocessor, but that doesn't mean that I SHOULD).
I guess I could define a non-templated base class, but my rusty C++ always fails me in this case (non-templated bases of template classes... when I do I need to use the template syntax in construction? there are non-obvious gotchas in this design).
Like I said, I'm sure someone else has invented this wheel; I'm re-rolling it mostly to force my aging, rusty-in-C++ brain to start thinking about things like this again.