且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从C ++调用Win32 DLL

更新时间:2023-10-12 23:41:04

的, 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 等。