Calling MASM32 procedure from .c

2019-03-02 22:10发布

问题:

I am using visual studio at the moment. I need to build a win32 application and need to call a procedure from a C function but I am always getting a build error:

Error 3 error LNK1120: 1 unresolved externals

I have reduced everything down to a simple main function and simple .asm file with one procedure and I am still getting the same build (or rather link) error. I'm at a loss.

Both are using the cdecl convention.

The MASM32 code (in its own .asm file):

.MODEL FLAT, C
.DATA              

.CODE      

PUBLIC memory_address

memory_address PROC 

    mov eax, DWORD PTR [esp] 

    ret

memory_address ENDP

END

It assembles fine. The .c file:

#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;
}

No idea why this is happening. I have been using MASM happily for 64bit application for about a year or so with no problems. But I have to make a 32bit application I am having no luck calling the MASM32 proc memory_address().

I hasten to add I know how to do this in NASM for 32 bit applications and I know how to do it for 64bit applications using MASM. This is strictly a MASM32 issue. Any suggestions would be great - but only for MASM32. Thanks.

回答1:

You can build your asm module as DLL.

Its easy to use STDCALL for all this, so instead:

.MODEL FLAT, C

you can use:

.model flat, stdcall

simply create additional to your yourmodule.asm a yourmodule.def file. Within that place these lines:

LIBRARY "yourmodule.dll"
EXPORTS memory_address

then use: ml.exe /c /coff yourmodule.asm Link.exe /SUBSYSTEM:CONSOLE /DLL /DEF:yourmodule.def yourmodule.obj

In your C++ application then remove:

extern int memory_address(int* ptr);

and add instead:

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
}

calling your function:

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

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

    // ....


标签: c masm32