MichaelMitchell
MichaelMitchell

Reputation: 1167

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.

Upvotes: 1

Views: 170

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

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);
    }
}

Upvotes: 1

CBHacking
CBHacking

Reputation: 2122

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();
    }
}

Upvotes: 1

Related Questions