问题描述
我是新的DLL世界。我已经给了一个Win32 DLL有很多功能。需要从C ++调用这些DLL函数
I am new to the DLL world. I have been given a Win32 DLL which has a lot of functions. Need to call these DLL functions from C++
我想调用 CreateNewScanner
,它创建一个新的扫描器对象,结果在C ++。
DLL中提到的函数是:
I want to call CreateNewScanner
which creates a new scanner object and get the results in C++.Function mentioned in the DLL is:
BOOL CreateNewScanner(NewScanner *newScan);
和 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;
如何调用此函数?从C ++开始,这是我管理的,
How will I call this function? Started with C++ and here is what I managed,
#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??
}
}
推荐答案
的, return-1
是不好的。您将返回一个整数。所以你肯定意味着 return -1
。
First of all, return "-1"
is no good. You are expected to return an integer. So you surely mean return -1
.
现在回答问题。代替将函数指针声明为 FARPROC
,它更容易声明为函数指针类型。
Now to the question. Instead of declaring the function pointer as FARPROC
, it's easier to declare it as a function pointer type.
typedef BOOL (*CreateNewScannerProc)(NewScanner*);
然后调用GetProcAddress如下:
Then call GetProcAddress like this:
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);
说完这些,通常一个库会带有一个头文件应包括它)和用于加载时链接的.lib文件。确保将.lib文件传递给链接器,您只需这样做:
Having said all of that, usually a library will come with a header file (yours clearly does so you should include it) and a .lib file for load-time linking. Make sure that you pass the .lib file to your linker and you can simply do this:
#include "NameOfTheHeaderFileGoesHere.h"
....
NewScanner newScan;
BOOL retval = CreateNewScanner(&newScan);
无需使用 LoadLibrary
GetProcAddress
等。
这篇关于从C ++调用Win32 DLL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!