using assembly code inside Objective c program (Xc

2020-02-29 07:46发布

问题:

Is there a way to use assembly code inside Objective C program. I am developing an application for OSX and wanted to use assembly code alongside the Objective C code. I searched the internet and found this But I am not able to implement any of these methods successfully. Any help will be greatly appreciated.

回答1:

Yes, of course.

You can use GCC-style inline assembly in Objective-C just like you would in C. You can also define functions in assembly source files and call them from Objective-C. Here's a trivial example of inline assembly:

int foo(int x, int y) {
    __asm("add %1, %0" : "+r" (x) : "r" (y));
    return x;
}

And a similarly minimal example of how to use a standalone assembly file:

** myOperation.h **
int myOperation(int x, int y);

** myOperation.s **
.text
.globl _myOperation
_myOperation:
    add %esi, %edi  // add x and y
    mov %edi, %eax  // move result to correct register for return value
    ret

** foo.c **
#include "myOperation.h"   // include header for declaration of myOperation
...
int x = 1, y = 2;
int z = myOperation(x, y); // call function defined in myOperation.s