技术宅,fat-man

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

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

统计

一篇旧文章,结合汇编探索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   codestyle  阅读(447)  评论(0编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
历史上的今天:
2013-01-17 项目设计阶段的一些事
点击右上角即可分享
微信分享提示