一些奇怪的函数指针转换

本文展示了如何在C++中使用函数指针、模板和类型转换来实现基类和派生类之间的功能调用,以及静态成员函数的处理。通过实例代码,读者可以了解这些概念的实际应用。
摘要由CSDN通过智能技术生成

#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;
}

话不多说,自己看代码编译运行体会。

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值