2016-07-30 60 views
1

我目前正在使用visual studio。我需要建立一個Win32應用程序,需要從C函數調用一個過程,但我總是得到一個編譯錯誤:從.c調用MASM32程序

錯誤3錯誤LNK1120:1周無法解析的外部

我把一切都降低到一個簡單的主函數和簡單的.asm文件與一個過程,我仍然得到相同的構建(或更確切地說,鏈接)的錯誤。我很茫然。

兩者都使用cdecl約定。

的MASM32代碼(在它自己的.asm文件):

.MODEL FLAT, C 
.DATA    

.CODE  

PUBLIC memory_address 

memory_address PROC 

    mov eax, DWORD PTR [esp] 

    ret 

memory_address ENDP 

END 

它組裝的罰款。 .c文件:

#include <stdlib.h> 
#include <malloc.h> 
#include <stdio.h> 

extern int memory_address(int* ptr); 

void main() 
{ 
    int *ptr = (int*)malloc(sizeof(int)); 

    memory_address(ptr); 

    while (1) {} 

    return; 
} 

不知道爲什麼會發生這種情況。我一直在使用MASM高興地爲64位應用程序大約一年左右沒有問題。但我必須做一個32位應用程序,我沒有運氣調用MASM32 proc memory_address()。

我急於添加我知道如何在NASM中爲32位應用程序執行此操作,我知道如何爲使用MASM的64位應用程序執行此操作。這完全是一個MASM32問題。任何建議都會很棒 - 但只適用於MASM32。謝謝。

+0

我知道你想爲MASM32答案,但你是怎麼在NASM做到這一點?你能證明嗎?只需編輯你的問題,以顯示工作的NASM代碼。 –

+2

嘗試添加一個前導下劃線到masm過程的名稱? – anatolyg

+1

另外,它是否提到它試圖找到的名稱,就在您引用錯誤之前? – anatolyg

回答

1

您可以將您的asm模塊構建爲DLL。

它易於使用STDCALL這一切, 這樣反而:

.MODEL FLAT, C 

你可以使用:

.model flat, stdcall 

簡單地創建附加到你的yourmodule.asm 一個yourmodule.def文件。 在那個地方這些行:

LIBRARY "yourmodule.dll" 
EXPORTS memory_address 

然後使用: ML.EXE/C/COFF yourmodule.asm LINK.EXE/SUBSYSTEM:CONSOLE/DLL /DEF:yourmodule.def yourmodule.obj

在你的C++應用程序,然後刪除:

extern int memory_address(int* ptr); 

,並添加代替:

typedef void*(__stdcall *PTRmemory_address)(int*); 
extern PTRmemory_address memory_address = NULL; // init as "NOT PRESENT" 

HMODULE yourmoduleHMODULE; 
yourmoduleHMODULE = GetModuleHandleA("yourmodule.dll"); // ensure valid file path! 
if (!yourmoduleHMODULE) 
    yourmoduleHMODULE = LoadLibraryA("yourmodule.dll"); // ensure valid file path! 

if (yourmoduleHMODULE) 
{ 
    memory_address = (PTRmemory_address)GetProcAddress(yourmoduleHMODULE, "memory_address"); 
    if (!memory_address) 
    { 
     printf("\n Cannot Find function memory_address in yourmodule.dll"); 
     exit(1); // exit application when function in DLL not found 
    } 
}  
else 
{ 
    printf("\n yourmodule.dll not found"); 
    exit(1); // exit application when DLL not found 
} 

調用你的函數:

int *ptr = (int*)malloc(sizeof(int)); 

if (memory_address) // ensure, that your function is present 
    memory_address(ptr); 
else 
    printf("\n error"); 

    // ....