简体   繁体   English

C ++-如何使其他类可以使用显式导入的DLL函数

[英]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() . 我有一个名为mydll.dll的dll,该dll中有一个名为testFunc()的函数。 I would like to have testFunc() available in other scopes outside of the scope where it is GetProcAddress() 'ed in. 我想在它是GetProcAddress()的作用域之外的其他作用域中使用testFunc()

For instance: 例如:

main.cpp 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 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. 我只是想要一种在代码中的任何地方使用testFunc()的方法,而不必从dll重新获取它。

Create a header file (myheader.h). 创建一个头文件(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. 明确定义变量并将其设置在main中。

myheader.h myheader.h

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

main.cpp main.cpp中

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

A.cpp A.cpp

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

I have tried to make a sample for the mentioned DLL wrapper class 我试图为提到的 DLL包装器类制作示例

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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