2010-12-05 131 views
1
#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); 
} 

將是真棒如果有人能解決在英特爾i7處理器的PC彙編的一部分,因爲它導致對我的Ubuntu :)彙編代碼

段錯誤這是把彙編代碼的最佳方式在交流計劃?

+0

雖然我不能說你的操作碼是否正確,但我知道它也可能因其他原因而崩潰。你知道你分配的內存是否可以用來執行代碼嗎?通常你用'malloc`得到的東西不能。 – detunized 2010-12-05 15:39:40

+0

我不知道:) – 2010-12-05 15:48:33

回答

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

可以在不使用typedef的情況下編寫它,但在不使用typedef的情況下強制轉換爲函數指針是非常難看的。

int (*testFuncPtr)(void); 

鑄造這個函數指針會使用

(int (*)(void))