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

C++ C++;-如何使显式导入的DLL函数可用于其他类,c++,dll,C++,Dll,我有一个名为mydll.dll的dll,在dll中有一个名为testFunc()的函数。我想让testFunc()在GetProcAddress()所在范围之外的其他范围中可用 例如: main.cpp #include <Windows.h> typedef void(*f_testFunc)(); int main(){ // load dll into hDll f_testFunc testFunc = (f_testFunc)GetProcAddress(h

我有一个名为
mydll.dll
的dll,在dll中有一个名为
testFunc()
的函数。我想让
testFunc()
GetProcAddress()
所在范围之外的其他范围中可用

例如:

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();
    }
}
class A{
    public:
    A(){
        testFunc();
    }
}
#include "myheader.h"
f_testfunc testFunc;
int main () {
    testFunc = (f_testFunc)GetProcAddress(hDll, "testFunc");
    for (int i ...
#include "myheader.h"
class A {
    public:
    A () {
        testFunc();
    }
}
我只想找到一种方法,在我的代码中的任何地方使用
testFunc()
,而不必从dll重新获取它。

创建一个头文件(myheader.h)。将函数变量声明为extern。在所有源文件中包含此标题。显式定义变量并在main中设置它

myheader.h

typedef void(*f_testFunc)();
extern f_testFunc testFunc;
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();
    }
}
class A{
    public:
    A(){
        testFunc();
    }
}
#include "myheader.h"
f_testfunc testFunc;
int main () {
    testFunc = (f_testFunc)GetProcAddress(hDll, "testFunc");
    for (int i ...
#include "myheader.h"
class A {
    public:
    A () {
        testFunc();
    }
}
A.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();
    }
}
class A{
    public:
    A(){
        testFunc();
    }
}
#include "myheader.h"
f_testfunc testFunc;
int main () {
    testFunc = (f_testFunc)GetProcAddress(hDll, "testFunc");
    for (int i ...
#include "myheader.h"
class A {
    public:
    A () {
        testFunc();
    }
}

我试图为DLL包装器类制作一个示例

 typedef void(*f_testFunc)();

 class DllWrapper {

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

 private:
      f_testFunc testFunc_;
 };


intmain(){
//将dll加载到hDll中
dllwraperdll(hDll);
for(int i=0;i
传递函数指针怎么样?@πνταῥεῖ 有没有一种方法可以通过头文件包含函数?您可以将函数指针的typedef放在头文件中,并在代码的其他地方使用它。应该调用此函数的类可以提供函数指针(抓取一次),例如在它们的构造函数中。@πάνταῥεῖ 是否有可能将导入函数的几个指针放在
结构中
?当然有可能。您还可以创建一个代理包装器类,在内部完成所有这些工作(获取函数指针等)。通常,当您构建共享库时,这种存根会由链接器自动生成。与CBHacking使用
extern
的示例相比,使用这种方法有什么好处?@MichaelMitchell它更灵活,特别是如果您想从这个DLL中拥有多个函数。此外,全局外部变量会使您的代码变得混乱,并使您更难了解幕后发生的事情。