简体   繁体   中英

assembler code in a c program

#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);
}

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 ac 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM