Reflection, or how to dynamically load functions from an external .dll library using LoadLibrary .



The whole reflection process is divided into several parts.

The first part is a library that will implement certain methods. These methods will be flagged as exportable methods.

The second part consists of a program that we use to load the library and use methods from it.
It is logical that in the part of the program, we must know what the methods are - their return type and input parameters. .

Algorithm :
1 . Declare pointre as a type for functions with the same input parameters and return value,
     as prototypes of functions in the .dll library.
2 . Use the LoadLibrary method to load the library into the operating memory from which you want to import
3 . Assign references to functions from the library retyped by pointers, via GetProccAddres .
4. Run pointers to functions (possibly with input parameters).


Library file: mydll.dll:
First, we need to declare prototypes of the functions we implement in the library in the library.
All function prototypes must be in the extern "C" block and include promacro __declspec (dllexport) at the beginning of the declaration.

   extern "C" {
       __declspec(dllexport) float GetFloat(int a, int b, int c);
       __declspec(dllexport) int Number(int a, int b);
       __declsúec(dllexport) void HelloWorld(void);

The "extern" keyword defines that functions should be extensible throughout solutions, and __declspec defines to the compiler that methods are intended not export. The compiler further creates a linker to the library in the form of the file mydll.lib.

After declaring the prototypes, we implement them.


   float GetFloat(int a, int b, int c)
       return 0.458 - (a + b) + 152.45 + c;
} int Number(int a, int b) { if(a > b) { return a; } else return b; }
void HelloWrld(void) { ::std::cout << "\n HelloWorld"; }

V programe program.exe:


   #include <windows.h>
   #include <fstream>
   #include <iostream>
   typedef float (*fnca)(int a, int b, int c);
   typedef int (*fncb)(int a, int b);
   typedef void (*fncc)(void);

   int _cdecl main (void)
       fnca dllfunctionA;
       fncb dllfunctionB;
       fncc dllfunctionC;

       HINSTANCE instance = LoadLibraryA("mydll.dll");
       dllfunctionA = (fnca)GetProcAddress(instance, "GetFloat");
       dllfunctionB = (fncb)GetProcAddress(instance, "Number");
       dllfunctionC = (fncc)GetProcAddress(instance, "HelloWorld");

       ::std::cout << dllfunctionA(8, 2, 5);
       ::std::cout << "\n";
       ::std::cout << dllfunctionB(50, 80);
       ::std::cout << "\n";
       dllfunctionC ();
       ::std::cout <<"\n\n";


       return 0;

The whole example is in the video here: