Calling MASM32 procedure from .c

前端 未结 1 1562
孤城傲影
孤城傲影 2021-01-24 10:34

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

相关标签:
1条回答
  • 2021-01-24 10:48

    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");
    
        // ....
    
    0 讨论(0)
提交回复
热议问题