技术宅,fat-man

增加语言的了解程度可以避免写出愚蠢的代码

导航

一篇旧文章,结合汇编探索this指针

//VC6.0下成功编译
#include <iostream.h>

class X{
public:
    void foo(int b,int c){
        this->a=b*c;
        cout<<a<<endl;
    }
    int a;
};

int main(){
    void (X::*pXfoo)(int,int);
    void (__stdcall*pfoo)(int,int);
    //协调调用约定 让被调函数进行栈的清理
    
    pXfoo = X::foo;
    __asm{
        push eax
        mov eax,dword ptr pXfoo
        mov dword ptr pfoo,eax
        pop  eax
        //pfoo = pXfoo
    }
    X x;

    //使用对象地址给this指针赋值
    __asm push ecx
    __asm lea ecx,x
    pfoo(3,4);
    __asm pop ecx
    //另一种类似__thiscall调用约定的是__fastcall
    //但是使用__fastcall,则所有参数将被放入寄存器,则成员函数产生异常
}

/*
    C++的成员函数就是个普通函数与C
    的函数的不同之处也就是调用约定的不同

    VC的__thiscall的特征:
    1)对象地址通过寄存器传递
    2)其他参数通过栈传递
    3)进栈方式 右 -> 左
    4)被调函数进行栈清理
*/

 

//BCB6.0 下成功编译
#include <iostream.h>

class X{
public:
    void foo(int b,int c){
            a = b*c;
            cout<<"a="<<a<<endl;
    }
    int a;
};

int main(){
    X x; //04
    void (X::*pXfoo)(int,int);//08
    void (*pfoo)(X* THIS,int,int);//0c~14

    pXfoo=X::foo;
   __asm{
        push eax
        mov eax,dword ptr pXfoo
        mov dword ptr pfoo,eax
        pop  eax
        //pfoo = pXfoo
    }

    pfoo(&x,3,4);
    getchar();
    //BCB __thiscall the same to __cdecl
} 

 

posted on 2014-01-17 18:19  codestyle  阅读(444)  评论(0编辑  收藏  举报