zoukankan      html  css  js  c++  java
  • gcc 在c代码中内嵌汇编调用c函数: 只是证明曾经我来过

    我怕我不写下来,将来我都不记得我还在 c 中嵌套过汇编语言,用汇编代码调用一个c函数的过程。

    折腾了一下午,在网上查看相关的资料,然后照葫芦画瓢地在c代码中嵌套汇编,希望解决我所遇到的问题,可最后发现全是徒劳。

    根据我的初步了解,在c中嵌套汇编来调用一个c函数的时候, 当c函数的参数过多时, 汇编代码没办法写, 好像对参数的数量有相当大的限制。

    下面的代码,如果我将c函数的参数增加到3个时, 汇编代码我就写不出来了,  并不能通过简单的在汇编代码中增加一个参数来实现。

    多增加一个参数,编译代码时,就会抛出错误:'asm' operand has impossible constraints|  ('asm'操作数有不可能的约束)

    我是彻底的放弃了,到此为止吧。

    int abc2(int a, int b)
    {
    printf("
    ");
    
    printf("参数a(%d): %d
    ", &a, a);
    printf("参数b(%d): %d
    ", &b, b);
    //printf("参数c(%d): %d
    ", &c, c);
    //printf("参数d(%d): %d
    ", &d, d);
    
    return a > b ? a : b;
    }
    
     
    
    int main(int argc, char *argv[])
    {
    void *saved_my_esp, *target_addr;
    unsigned int return_eax, return_edx;
    
    void *func = abc2;
    
    int a = 10;
    int b = 20;
    int c = 30;
    int d = 40;
    
    printf("&a:%d
    ", &a);
    printf("&b:%d
    ", &b);
    printf("&func:%d
    ", func);
    
    
    //参考: https://bbs.csdn.net/topics/360148698
    
    
    __asm__ __volatile__ (
    
    "movl %%esp, %0;"
    
    "movl %3, %%eax;" //变量: d
    "push %%eax;"
    
    "movl %4, %%eax;" //变量: c
    "push %%eax;"
    
    
    "movl %5, %%eax;" //函数
    "call *%%eax;"
    
    "mov %%eax, %1;"
    "mov %%edx, %2;"
    "movl %0, %%eax;"
    
    //"movl %%eax, %%esp;" /** 加这一句, 就出错 **/
    
    : "+m" (saved_my_esp), "=m" (return_eax), "=m" (return_edx)
    
    : "r"(b), "r"(a), "r"(func) // 关于 m, r 说明: https://www.cnblogs.com/Jezze/archive/2011/12/23/2299838.html
    
    : "%eax", "%edx", "%esp"
    );
    
    printf("saved_my_esp:%d
    ", saved_my_esp);
    printf("return_eax:%d
    ", return_eax);
    printf("return_edx:%d
    ", return_edx);
    
    printf("
    ");
    
    //printf("return_value:'%s'
    ", return_eax
    //printf("return_value:%d
    ", *(int *)return_eax);
    //printf("return_value:%lf
    ", *(float *)return_eax);
    //printf("return_value:%d
    ", *(BYTE *)return_eax);
    
    printf("return_value:%d
    ", return_eax);
    
    printf("
    ");
    
    printf("------------------end-------------
    ");
    
    return 0;
    
    }
  • 相关阅读:
    【leetcode】416. Partition Equal Subset Sum
    【leetcode】893. Groups of Special-Equivalent Strings
    【leetcode】892. Surface Area of 3D Shapes
    【leetcode】883. Projection Area of 3D Shapes
    【leetcode】140. Word Break II
    【leetcode】126. Word Ladder II
    【leetcode】44. Wildcard Matching
    【leetcode】336. Palindrome Pairs
    【leetcode】354. Russian Doll Envelopes
    2017.12.22 英语面试手记
  • 原文地址:https://www.cnblogs.com/personnel/p/11414480.html
Copyright © 2011-2022 走看看