#include <cstdint>
#include <type_traits>
#include <utility>
#include <iostream>
typedef struct base {
} base_t;
class Derived : public base_t {
public:
int32_t DerivedFunction(uint32_t i, uint32_t j,
int32_t *k)
{
std::cout << "DerivedFunction" << std::endl;
return 0;
}
};
typedef int32_t (*function_pointer)(
base_t* obj, uint32_t i, uint32_t j,
int32_t* k);
typedef void (*void_function_pointer_t)();
static Derived *toDerived(base_t *obj) {
return static_cast<Derived *>(obj);
}
template <typename T, typename HookType, HookType func, typename... Args>
static T BaseHook(base_t *obj, Args... args) {
Derived *derivedObj = toDerived(obj);
return static_cast<T>(((*derivedObj).*func)(std::forward<Args>(args)...));
}
template <typename PFN, typename T>
static void_function_pointer_t ToHook(T function) {
static_assert(std::is_same<PFN, T>::value, "Incompatible fn pointer");
return reinterpret_cast<void_function_pointer_t>(function);
}
typedef void (*function_pointer_t)(int, int);
template <typename T>
static function_pointer_t MyToHook(T function) {
return reinterpret_cast<function_pointer_t>(function);
}
typedef void (*function_pointer_t2)();
template <typename T>
static function_pointer_t2 MyToHook2(T function) {
return reinterpret_cast<function_pointer_t2>(function);
}
int32_t xxx(int a, int b){
std::cout << "xxx" << std::endl;
std::cout << a+b << std::endl;
return 0;
}
int main()
{
void_function_pointer_t pfn = ToHook<function_pointer>(
BaseHook<int32_t, decltype(&Derived::DerivedFunction),
&Derived::DerivedFunction, uint32_t, uint32_t,
int32_t *>);
pfn();
auto pfn1 = MyToHook(xxx);
pfn1(1, 2);
auto pfn2 = MyToHook2(xxx);
pfn2();
return 0;
}
话不多说,自己看代码编译运行体会。