获取函数地址并调用函数

最简单的直接测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using namespace std;

void test() {
cout << "DONE!" << endl;
}

int main() {
cout << test << endl;
void (*myCALL)();
myCALL = test;
(*myCALL)();
cout << *myCALL << endl;
return 0;
}

从数组中获取地址并调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <vector>

using namespace std;

void test() {
cout << "DONE!" << endl;
}

void callFunc(int x) {
void (*pro)();
pro = (void (*)()) x;
(*pro)();
}

int main() {
vector<int> address;
address.push_back(int(test));
cout << test << endl;
callFunc(address[0]);
return 0;
}

获取类成员函数地址并调用$^{1}$

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>

using namespace std;

class A
{
public:
void fn() {
cout << "myCallFunc is Done~" << endl;
}
};

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

long getAddress(decltype (&A::fn) x)
{
void* ptr = pointer_cast<void*>(x);
return (long)ptr;
}

void callFunc(long x) {
void (*pro)();
pro = (void(*)()) x;
(*pro)();
}

int main(void)
{
long address = getAddress(&A::fn);
callFunc(address);
return 0;
}

对应的函数模板与使用方法

getAddress

1
2
3
4
5
6
template<typename dst_type, typename src_type>
dst_type getAddress(src_type x)
{
void* ptr = pointer_cast<void*>(x);
return (dst_type)ptr;
}
1
long address = (long)getAddress<void*>(&FuncFlowT::funcA);

callFunc

1
2
3
4
5
6
template<typename src_type>
void callFunc(src_type x) {
void (*pro)();
pro = (void(*)()) x;
(*pro)();
}
1
callFunc<long>(address);

Reference

  1. https://www.cnblogs.com/memset/p/get_member_function_address_cpp.html

  2. https://bbs.csdn.net/topics/80149694



----------- 本文结束 -----------




0%