Created
          November 9, 2017 09:35 
        
      - 
      
- 
        Save rdeioris/029df0bdb74e47ac8407574521c5e439 to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | #include <stdio.h> | |
| #ifdef _WIN32 | |
| #include <windows.h> | |
| #else | |
| #include <dlfcn.h> | |
| #endif | |
| #ifdef _WIN32 | |
| #define EXPORT __declspec(dllexport) | |
| #else | |
| #define EXPORT | |
| #endif | |
| EXPORT int multiplier(int a, int b) | |
| { | |
| return a * b; | |
| } | |
| EXPORT void *aiv_open_lib(const char *name) | |
| { | |
| #ifdef _WIN32 | |
| // get address of the current process symbols table | |
| if (name == NULL) | |
| return GetModuleHandle(NULL); | |
| return LoadLibrary(name); | |
| #else | |
| return dlopen(name, RTLD_LAZY); | |
| #endif | |
| } | |
| EXPORT void *aiv_lib_symbol(void *lib, const char *name) | |
| { | |
| #ifdef _WIN32 | |
| return GetProcAddress(lib, name); | |
| #else | |
| return dlsym(lib, name); | |
| #endif | |
| } | |
| static int call_add(int a, int b) | |
| { | |
| void *plugin = aiv_open_lib("libfoo.dll"); | |
| if (!plugin) | |
| { | |
| fprintf(stderr, "adder() is not implemented\n"); | |
| return -1; | |
| } | |
| int (*adder)(int, int) = aiv_lib_symbol(plugin, "adder"); | |
| if (!adder) | |
| { | |
| fprintf(stderr, "adder() is not implemented\n"); | |
| return -1; | |
| } | |
| // adder is now a valid function pointer | |
| fprintf(stdout, "plugin loaded at %p: %d\n", plugin, adder(a, b)); | |
| return -1; | |
| } | |
| int main(int argc, char *argv[]) | |
| { | |
| fprintf(stdout, "hello i am main()\n"); | |
| call_add(17, 22); | |
| void *myself = aiv_open_lib(NULL); | |
| fprintf(stdout, "myself available at %p\n", myself); | |
| fprintf(stdout, "multiplier is at address %p\n", aiv_lib_symbol(myself, "multiplier")); | |
| fprintf(stdout, "aiv_open_lib is at address %p\n", aiv_lib_symbol(myself, "aiv_open_lib")); | |
| fprintf(stdout, "aiv_lib_symbol is at address %p\n", aiv_lib_symbol(myself, "aiv_lib_symbol")); | |
| return 0; | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment