c程序中的汇编代码

时间:2010-12-05 15:27:24

标签: c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main()
{
 typedef int (FuncPtr)();
 char asmFunc[] = {0x90, 0xB8, 0x10, 0x00, 0x00, 0x00, 0xC3};
 FuncPtr *cFunc = malloc(7);
 memmove(cFunc, asmFunc, 7);
 int result = cFunc();
 printf("result = %d\n", result);
}

如果有人可以在intel i7 pc上修复汇编程序部分会很棒,因为它会导致我的ubuntu出现段错误:)

这是将汇编代码放入c程序的最佳方法吗?

3 个答案:

答案 0 :(得分:4)

将汇编代码放入C源文件的最佳方法是使用内联汇编。这是一个很好的starting point。例如:

int main(void)
{
 int x = 10, y;

 asm ("movl %1, %%eax;"
      "movl %%eax, %0;"
  :"=r"(y) /* y is output operand */
  :"r"(x)  /* x is input operand */
  :"%eax"); /* %eax is clobbered register */
}

答案 1 :(得分:2)

可以在没有typedef的情况下编写它,但是在没有typedef的情况下强制转换为函数指针非常难看。

int (*testFuncPtr)(void);

使用

转换为此函数指针
(int (*)(void))

答案 2 :(得分:1)

嗯,这肯定不是将机器代码包含在C程序中的最佳方法。使用内联汇编。既然你遇到了Ubuntu,我会提到 gcc 完全可以做到这一点。

首先看http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html