开发者

assembler code in a c program

#include <stdio.h>
#include <stdlib.h>
#include <str开发者_开发技巧ing.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);
}

Would be awesome if somebody could fix the assembler part on a intel i7 pc because it result in a segfault on my ubuntu :)

Is this the best way to put assembler code in a c program?


Best way to put assembly code in a C source file would be to use inline assembly. Here's a good starting point. Example:

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 */
}


It is possible to write it without the typedef but casts to function pointers without typedef are very ugly.

int (*testFuncPtr)(void);

Casting to this function pointer would be done using

(int (*)(void))


Well, it certainly is not the best way to include machine code into your C program. Use inline assembly. Since you metnion Ubuntu, I will mention that gcc is perfectly able to do that.

See http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html for a start.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜