[問題] __asm呼叫function的問題

看板C_and_CPP作者 (SurprisingTW)時間12年前 (2012/05/26 22:35), 編輯推噓0(0014)
留言14則, 3人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) VC 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) __asm 問題(Question): 如何正確的使用__asm呼叫其他function? 餵入的資料(Input): 12345 預期的正確結果(Expected Output): 120 錯誤結果(Wrong Output): http://ppt.cc/Z~F5 程式碼(Code):(請善用置底文網頁, 記得排版) #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; int q[5]={1,2,3,4,5}; void test(int* q, int p, int r) { __asm { mov eax, q mov ebx, p mov ecx, r mov edx, 1 call factorial } return; __asm { factorial: cmp ebx, ecx jae quit mov edi, [eax+ebx] imul edx, edi add ebx, 4 jmp factorial quit: mov [eax], edx //乘完的數放回q[0] } } void main() { test(q, 0, 5); cout << q[0] << endl; system("pause"); } 補充說明(Supplement): 其實就是想用__asm的方式來寫C++的函式呼叫 有看過別人用這樣的方式寫function 可是自己寫不出來 不知道錯在哪 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.43.162.62

05/26 22:38, , 1F
你用call的話function內要用ret
05/26 22:38, 1F

05/26 22:38, , 2F
因為call是push eip+4 & jmp
05/26 22:38, 2F

05/26 22:58, , 3F
可能也要pushad一下,這樣亂用暫存器不怎麼安全
05/26 22:58, 3F

05/26 23:07, , 4F
也是~那也要記得popad XDD
05/26 23:07, 4F

05/26 23:12, , 5F
話說回來ebx是+4, 所以應該要跟ecx*4比 或是把5改成20
05/26 23:12, 5F

05/26 23:13, , 6F
話說回來那個return好像也沒問題 畢竟沒用到test沒用到
05/26 23:13, 6F

05/26 23:14, , 7F
local varible所以test裡面compiler幫你做的leave其實是
05/26 23:14, 7F

05/26 23:14, , 8F
是leave 0? XD
05/26 23:14, 8F

05/26 23:21, , 9F
欸不對..預設是cdecl..是callee要負責清stack orz
05/26 23:21, 9F

05/27 00:31, , 10F
唔...有範例能看一下嗎?
05/27 00:31, 10F

05/27 01:05, , 11F
call factorial 下面加一個pop eax看看
05/27 01:05, 11F

05/27 01:07, , 12F
mov [eax], edx 下面加一條retn
05/27 01:07, 12F

05/27 01:08, , 13F
應該是加個retn就OK了
05/27 01:08, 13F

05/27 10:40, , 14F
還是一樣的錯誤耶T_T
05/27 10:40, 14F
文章代碼(AID): #1FmEego- (C_and_CPP)