获取C++成员函数地址

66 篇文章 0 订阅
54 篇文章 0 订阅

参考文章:https://www.cnblogs.com/nbsofer/p/get_member_function_address_cpp.html

AppleDemo.h:

class CAppleDemo
{
public:
	CAppleDemo();
	~CAppleDemo();

	void fun1(void);

	void fun2(int a, int b);

	int fun3(int a);
};

AppleDemo.cpp

#include "stdafx.h"
#include "AppleDemo.h"
#include <iostream>

CAppleDemo::CAppleDemo()
{
	std::cout << "CAppleDemo::CAppleDemo()" << std::endl;
}


CAppleDemo::~CAppleDemo()
{
	std::cout << "CAppleDemo::~CAppleDemo()" << std::endl;
}

void CAppleDemo::fun1(void)
{
	std::cout << "CAppleDemo::fun1()" << std::endl;
}

void CAppleDemo::fun2(int a, int b)
{
	std::cout << "CAppleDemo::fun2() a=" << a << " b=" << b << std::endl;
}

int CAppleDemo::fun3(int a)
{
	std::cout << "CAppleDemo::fun3() a=" << a  << std::endl;
	return a;
}

 

main.cpp

#include "stdafx.h"
#include<stdio.h>
#include <stdlib.h>
#include "AppleDemo.h"

//https://www.cnblogs.com/nbsofer/p/get_member_function_address_cpp.html

template<typename dst_type, typename src_type>
dst_type pointer_cast(src_type src)
{
	return *static_cast<dst_type*>(static_cast<void*>(&src));
}

template<typename dst_type, typename src_type>
dst_type union_cast(src_type src)
{
	union{
		src_type s;
		dst_type d;
	}u;
	u.s = src;
	return u.d;
}

typedef void (__fastcall *FunFun1)(void* pThis, int edx);
typedef void (__fastcall *FunFun2)(void* pThis, int edx, int a, int b);
typedef int  (__fastcall *FunFun3)(void* pThis, int edx, int a);

int _tmain(int argc, _TCHAR* argv[])
{

	CAppleDemo cAppleDemo;

	
	FunFun1 fun1 = pointer_cast<FunFun1>(&CAppleDemo::fun1);
	FunFun2 fun2 = pointer_cast<FunFun2>(&CAppleDemo::fun2);
	FunFun3 fun3 = union_cast<FunFun3>(&CAppleDemo::fun3);

	fun1(NULL, NULL);
	fun2(NULL, NULL, 11, 22);
	fun3(NULL, NULL, 33);

	//cAppleDemo.fun1();
	//cAppleDemo.fun2(11, 22);
	//cAppleDemo.fun3(33);

	getchar();
	return 0;
}

效果如下:

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

friendan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值