使用.dll的方法

时间:2013-06-25 16:29:47

标签: c++ dll

有人可以帮我这个代码吗?

我想使用我在.Dll中声明的方法...我可以使用其中两种方法,但其中一种方法给我带来了很多麻烦...... 请遵循以下代码:

main.h - > DLL

 #ifndef _DLLTEST_H_
 #define _DLLTEST_H_

 #include <iostream>
 #include <stdio.h>
 #include <windows.h>

 extern "C" __declspec(dllexport) void NumberList();
 extern "C" __declspec(dllexport) void LetterList();
 extern "C" __declspec(dllexport) int sumNumber(int, int);


 #endif

main.cpp - &gt; DLL

 #include "main.h"

 #define MAXMODULE 50

using namespace std;

 char module[MAXMODULE];


 extern "C" __declspec(dllexport)

 void NumberList() {

       GetModuleFileName(NULL, (LPTSTR)module, MAXMODULE);

       cout << "\n\nThis function was called from "
            << module
            << endl << endl;

       cout << "NumberList(): ";


       for(int i=0;  i<10; i++) {

            cout << i << " ";
       }

       cout << endl << endl;

 }



 extern "C" __declspec(dllexport)

 void LetterList() {

       GetModuleFileName(NULL, (LPTSTR)module, MAXMODULE);

       cout << "\n\nThis function was called from "
            << module
            << endl << endl;

       cout << "LetterList(): ";


       for(int i=0;  i<26; i++) {

            cout << char(97 + i) << " ";
       }

       cout << endl << endl;
 }


extern "C" __declspec(dllexport)

int sumNumber(int i, int j) {


    cout << "Number: " << i + j << endl;

    return i+j;
}

测试我的.DLL

#define MAXMODULE 50

using namespace std;

 typedef void (WINAPI*cfunc)();

 cfunc NumberList;
 cfunc LetterList;
 cfunc sumNumber;

 int main() {

       HINSTANCE hLib=LoadLibrary("libCriandoDLL.dll");


       if(hLib==NULL) {

            cout << "Unable to load library!" << endl;
            getch();
       }

       char mod[MAXMODULE];

       GetModuleFileName((HMODULE)hLib, (LPTSTR)mod, MAXMODULE);
       cout << "Library loaded: " << mod << endl;


       NumberList=(cfunc)GetProcAddress((HMODULE)hLib, "NumberList");
       LetterList=(cfunc)GetProcAddress((HMODULE)hLib, "LetterList");
       sumNumber=(cfunc)GetProcAddress((HMODULE)hLib, "sumNumber");

       if((NumberList==NULL) || (LetterList==NULL) || (sumNumber==NULL)) {

            cout << "Unable to load function(s)." << endl;
            FreeLibrary((HMODULE)hLib);
       }


       NumberList();
       LetterList();
       sumNumber(1,1);

       FreeLibrary((HMODULE)hLib);

       getch();
 }

方法“NumberList();”和“LetterList();”完美地工作......然而,当我尝试使用方法“sumNumber(1.1)”时,他给出了以下错误: “错误:函数的参数太多了”

1 个答案:

答案 0 :(得分:2)

您将导入的函数声明为不带参数且不返回值:

 typedef void (WINAPI*cfunc)();

 cfunc NumberList;
 cfunc LetterList;
 cfunc sumNumber;

声明sumNumber正确属于int (WINAPI*)(int,int)类型,你会没事的。