Gert Cuykens
Gert Cuykens

Reputation: 7175

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 a c program?

Upvotes: 1

Views: 393

Answers (3)

detunized
detunized

Reputation: 15299

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

Upvotes: 4

Jim Brissom
Jim Brissom

Reputation: 32969

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.

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318718

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))

Upvotes: 2

Related Questions