简体   繁体   中英

C++ - How do you make Explicitly Imported DLL functions available to other classes

I have a dll called mydll.dll , in the dll there is a function called testFunc() . I would like to have testFunc() available in other scopes outside of the scope where it is GetProcAddress() 'ed in.

For instance:

main.cpp

#include <Windows.h>
typedef void(*f_testFunc)();
int main(){
    // load dll into hDll
    f_testFunc testFunc = (f_testFunc)GetProcAddress(hDll, "testFunc");

    for (int i = 0; i < NUM; i++){
        A a = A();
    }
}

A.cpp

class A{
    public:
    A(){
        testFunc();
    }
}

I simply want a way to use testFunc() anywhere in my code without having to re-grab it from the dll.

Create a header file (myheader.h). Declare the function variable there, as extern. Include this header in all your source files. Explicitly define the variable and set it in main.

myheader.h

typedef void(*f_testFunc)();
extern f_testFunc testFunc;

main.cpp

#include "myheader.h"
f_testfunc testFunc;
int main () {
    testFunc = (f_testFunc)GetProcAddress(hDll, "testFunc");
    for (int i ...

A.cpp

#include "myheader.h"
class A {
    public:
    A () {
        testFunc();
    }
}

I have tried to make a sample for the mentioned DLL wrapper class

 typedef void(*f_testFunc)();

 class DllWrapper {

      DllWrapper(HDLL hDll) {
          testFunc_ = (f_testFunc)GetProcAddress(hDll, "testFunc");
      }
      void testFunc() {
          (*testFunc_)();
      }

 private:
      f_testFunc testFunc_;
 };

 class A {
 public:
     A(DllWrapper& dll) dll_(dll) {
          dll_.testFunc();
     }

 private:
     DllWrapper& dll_;
 };

int main(){
    // load dll into hDll
    DllWrapper dll(hDll);

    for (int i = 0; i < NUM; i++){
        A a = A(dll);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM