【问题标题】:manipulating c variable via inline assembly [duplicate]通过内联汇编操作c变量[重复]
【发布时间】:2013-01-31 15:07:32
【问题描述】:

可能重复:
How to access c variable for inline assembly manipulation

鉴于此代码:

#include <stdio.h>

int main(int argc, char **argv)
{
  int x = 1;
  printf("Hello x = %d\n", x);


  }

我想访问和操作内联汇编中的变量 x。理想情况下,我想使用内联汇编来改变它的值。 GNU 汇编器,并使用 AT&T 语法。假设我想在 printf 语句之后将 x 的值更改为 11,我该怎么做?

【问题讨论】:

标签: c assembly inline-assembly


【解决方案1】:

asm() 函数遵循以下顺序:

asm ( "assembly code"
           : output operands                  /* optional */
           : input operands                   /* optional */
           : list of clobbered registers      /* optional */
);

并通过您的 c 代码将 11 放到 x 中:

int main()
{
    int x = 1;

    asm ("movl %1, %%eax;"
         "movl %%eax, %0;"
         :"=r"(x) /* x is output operand and it's related to %0 */
         :"r"(11)  /* 11 is input operand and it's related to %1 */
         :"%eax"); /* %eax is clobbered register */

   printf("Hello x = %d\n", x);
}

您可以通过避免破坏寄存器来简化上述 asm 代码

asm ("movl %1, %0;"
    :"=r"(x) /* related to %0*/
    :"r"(11) /* related to %1*/
    :);

您可以通过避免输入操作数并使用 asm 中的局部常量值而不是 c 中的值来简化更多:

asm ("movl $11, %0;" /* $11 is the value 11 to assign to %0 (related to x)*/
    :"=r"(x) /* %0 is related x */
    :
    :);

另一个例子:compare 2 numbers with assembly

【讨论】:

猜你喜欢
  • 2016-09-11
  • 1970-01-01
  • 2013-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多