从C++调用Win32 DLL

Cha*_*ata 2 c++ dll winapi

我是DLL世界的新手.我得到了一个Win32 DLL,它有很多功能.需要从C++调用这些DLL函数

我想调用CreateNewScanner哪个创建一个新的扫描仪对象并在C++中获得结果.DLL中提到的函数是:

BOOL CreateNewScanner(NewScanner *newScan);
Run Code Online (Sandbox Code Playgroud)

NewScanner是一个struct,如以下,

// Structure NewScanner is defined in "common.h" .
typedef struct{
  BYTE host_no; // <- host_no =0
  LONG time; // <- command timeout (in seconds)
  BYTE status; // -> Host adapter status
  HANDLE obj; // -> Object handle for the scanner
}NewScanner;
Run Code Online (Sandbox Code Playgroud)

我该怎么称呼这个功能?从C++开始,这是我管理的,

#include <iostream>
#include <windows.h>
using namespace std;
int main(){
  HINSTANCE hInstance;    
  if(!(hInstance=LoadLibrary("WinScanner.dll"))){
      cout << "could not load library" << endl;        
  }
  /* get pointer to the function in the dll*/
  FARPROC handle = GetProcAddress(HMODULE(hInstance), "CreateNewScanner");
  if(!handle){
    // Handle the error
    FreeLibrary(hInstance);
    return "-1";
  }else{    
    // Call the function
    //How to call here??
  }
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*nan 5

首先,return "-1"没有好处.您应该返回一个整数.所以你肯定是这个意思return -1.

现在回答这个问题.不是将函数指针声明为FARPROC,而是将其声明为函数指针类型更容易.

typedef BOOL (*CreateNewScannerProc)(NewScanner*);
Run Code Online (Sandbox Code Playgroud)

然后像这样调用GetProcAddress:

HMODULE hlib = LoadLibrary(...);
// LoadLibrary returns HMODULE and not HINSTANCE
// check hlib for NULL

CreateNewScannerProc CreateNewScanner = 
    (CreateNewScannerProc) GetProcAddress(hlib, "CreateNewScanner");
if (CreateNewScanner == NULL)
    // handle error

// now we can call the function
NewScanner newScan;
BOOL retval = CreateNewScanner(&newScan);
Run Code Online (Sandbox Code Playgroud)

说完所有这些之后,通常一个库会带有一个头文件(你显然应该包含它)和一个用于加载时链接的.lib文件.确保将.lib文件传递给链接器,您只需执行以下操作:

#include "NameOfTheHeaderFileGoesHere.h"
....
NewScanner newScan;
BOOL retval = CreateNewScanner(&newScan);
Run Code Online (Sandbox Code Playgroud)

不需要乱搞LoadLibrary,GetProcAddress等等.