Export a function, convert it to a pointer through a DLL

This is the development of an earlier question: How to reset the state of a machine during unit testing C
There is also a similar question, but I do not answer my problem, and I have some examples that I want to introduce: Exporting a function pointer from dll

I have two sets of code that I expect should do the same, but the last one crashes. Using mingw32 and win7.

Function to be exported. This should be considered a legacy and unchanging.
addxy.c

    int addXY(int x, int y)
    {
      return x + y;
    }    

addxy.h

    int addXY(int x, int y);

Working example

main.c

    #include <stdio.h>
    #include "addxy.h"

    typedef int (__cdecl *addXYWrap_t)(int a, int b);

    addXYWrap_t addXYWrap = (addXYWrap_t)addXY;

    void main()
    {
      printf("result: %d", addXYWrap(3, 4));
    }

Yielding

result: 7

Failure example

addxydll.c

    #include <stdio.h>
    #include "addxy.h"

    typedef int (__cdecl *addXYWrap_t)(int a, int b);

    __declspec(dllexport) addXYWrap_t addXYWrap = (addXYWrap_t)addXY;

main.c

    #include <windows.h>
    #include <stdio.h>

    typedef int (__cdecl *func)(int a, int b);

    void main()
    {
      HINSTANCE loadedDLL = LoadLibrary("addxy.dll");

      if(!loadedDLL) {
        printf("DLL not loaded");
        return;
      } else {
        printf("DLL loaded\n");
      }

      func addition = (func)GetProcAddress(loadedDLL, "addXYWrap");

      if(!addition) {
        printf("Func not loaded");
        return;
      } else {
        printf("Func loaded\n");
      }

      printf("result: %d", addition(3, 4));
    }

Yielding

DLL loaded
Func loaded

before it starts to break.

, .
?

0
3
func addition = (func)GetProcAddress(loadedDLL, "addXYWrap");

GetProcAddress addXYWrap, . addXYWrap ( , func), , func*.

:

func addition = *(func*)GetProcAddress(loadedDLL, "addXYWrap");

 

, :

func* addition = (func*)GetProcAddress(loadedDLL, "addXYWrap");

(*addition)(3, 4)

+1

, , , , . , GetProcAddress :

func addition = *(func*)GetProcAddress(loadedDLL, "addXYWrap");

, :

__declspec(dllexport) int myAddXY(int x, int y)
{
    return addXY(x, y);
}
0
int addXY(int x, int y)
{
  return x + y;
}
__declspec(dllexport) addXYWrap_t addXYWrap = (addXYWrap_t)addXY;

This is mistake. You need to export a function, not a global pointer. I.e

/* addxy.c */
__declspec(dllexport) int addXY(int x, int y)
{
  return x + y;
}
....
/* main.c */
func addition = (func)GetProcAddress(loadedDLL, "_addXY");
-1
source

Source: https://habr.com/ru/post/1614428/


All Articles