Posted on 2019-11-28 11:05
jacky_zz 阅读(178)
评论(0) 编辑 收藏 引用
base.h
1 #ifndef BASE_H
2 #define BASE_H
3
4 #include <stdio.h>
5
6 class Base
7 {
8 public:
9 Base(int val) : m_val(val)
10 {
11 printf("Base::Base(int val) @ 0x%08X\n", this);
12 }
13
14 virtual void say()
15 {
16 printf("void Base::say() @ 0x%08X\n", this);
17 printf("val = %d\n", GetVal());
18 }
19
20 virtual ~Base()
21 {
22 printf("Base::~Base() @ 0x%08X\n", this);
23 }
24
25 protected:
26 int GetVal() { return m_val; }
27
28 private:
29 int m_val;
30 };
31
32 #endif
child.h
1 #ifndef CHILD_H
2 #define CHILD_H
3
4 #include <stdio.h>
5 #include "base.h"
6
7 class Child : public Base
8 {
9 public:
10 Child(int val) : Base(val)
11 {
12 printf("Child::Child(int val) @ 0x%08X\n", this);
13 }
14
15 void say()
16 {
17 printf("void Child::say() @ 0x%08X\n", this);
18 printf("val = %d\n", GetVal());
19 }
20
21 ~Child()
22 {
23 printf("Child::~Child() @ 0x%08X\n", this);
24 }
25 };
26
27 #endif
28
main.cpp
1 #include "base.h"
2 #include "child.h"
3
4 static void test0();
5 static void test();
6 static void virfunc_call(Base *base);
7
8 void test0()
9 {
10 int src = 1;
11 int dst;
12
13 #ifdef WIN32
14 dst = src;
15 #else
16 asm ("mov %1, %0\n\t"
17 "add $1, %0"
18 : "=r" (dst)
19 : "r" (src));
20 #endif
21
22 printf("dst=%d\n", dst);
23 }
24
25 void test(Base *base)
26 {
27 int addr = 0;
28
29 #ifdef WIN32
30 printf("[1] addr=0x%08X base=0x%P\n", addr, base);
31 #else
32 printf("[1] addr=0x%08X base=0x%08X\n", addr, base);
33 #endif
34
35 #ifdef WIN32
36 addr = *((int *)base);
37 #else
38 asm (
39 "movl %0, %1\n\t"
40 : "=r" (addr)
41 : "r" (base)
42 );
43 #endif
44
45 #ifdef WIN32
46 printf("[2] addr=0x%08X base=0x%P\n", addr, base);
47 #else
48 printf("[2] addr=0x%08X base=0x%08X\n", addr, base);
49 #endif
50 }
51
52 static void virfunc_call(Base *base)
53 {
54 typedef void (*FUNC)();
55
56 int *pAddrBase = (int *)base;
57 int addr = *(int *)base;
58 int *pVirtualFuncBase = (int *)(*pAddrBase);
59
60 #ifdef WIN32
61 printf("\nvirfunc=0x%P\npAddrBase=0x%P\npVirtualFuncBase=0x%P\n\n", virfunc_call, pAddrBase, pVirtualFuncBase);
62 #else
63 printf("\nvirfunc=0x%08X\npAddrBase=0x%08X\npVirtualFuncBase=0x%08X\n\n", virfunc_call, pAddrBase, pVirtualFuncBase);
64 #endif
65
66 FUNC func = reinterpret_cast<FUNC>(*pVirtualFuncBase);
67
68 #ifdef WIN32
69 __asm {
70 mov ecx, base
71 }
72 #else
73 __asm__ __volatile__(
74 "movl %0, %%ecx"
75 :
76 : "r" (base)
77 :
78 );
79 #endif
80
81 func();
82 }
83
84 int main(int argc, char *argv[])
85 {
86 Base *base1 = nullptr, *base2 = nullptr;
87
88 base1 = new Base(1);
89 // base1->say();
90 virfunc_call(base1);
91 // test(base1);
92 delete base1;
93
94 base2 = new Child(2);
95 // base2->say();
96 virfunc_call(base2);
97 // test(base2);
98 delete base2;
99
100 return 0;
101 }
VC++
cl /DWIN32 main.cpp
G++
g++ -o main main.cpp