visual studio 2013 中动态库(dll)的引用方法

来源:互联网 发布:如何让淘宝客服介入 编辑:程序博客网 时间:2024/05/10 21:09

1、隐式连接

1.1 在dll的代码中加入:__declspec(dllexport),代码如下:

class __declspec(dllexport) CMyDllClass{public:CMyDllClass();~CMyDllClass();public:// Returns a + bstatic  double Add(double a, double b);// Returns a - bstatic  double Subtract(double a, double b);// Returns a * bstatic  double Multiply(double a, double b);// Returns a / b// Throws const std::invalid_argument& if b is 0static  double Divide(double a, double b);};

1.2 在工程属性中添加dll工程:

1.3添加引用代码:

#include "stdafx.h"#include <iostream>using namespace std;#include "../MyDll/MyDllClass.h"class __declspec(dllimport) CMyDllClass;int _tmain(int argc, _TCHAR* argv[]){CMyDllClass *lpcc = new CMyDllClass();cout << CMyDllClass::Add(1.0, 2.2) <<endl<< lpcc->Multiply(5.5,10)<<endl;getchar();return 0;}


2、显示连接

2.1调用 LoadLibrary(或相似的函数)以加载 DLL 和获取模块句柄

2.2调用 GetProcAddress,以获取指向应用程序要调用的每个导出函数的函数指针。由于应用程序是通过指针调用 DLL 的函数,编译器不生成外部引用,故无需与导入库链接

2.3使用完 DLL 后调用 FreeLibrary

2.4官方示例:

typedef UINT (CALLBACK* LPFNDLLFUNC1)(DWORD,UINT);...HINSTANCE hDLL;               // Handle to DLLLPFNDLLFUNC1 lpfnDllFunc1;    // Function pointerDWORD dwParam1;UINT  uParam2, uReturnVal;hDLL = LoadLibrary("MyDLL");if (hDLL != NULL){   lpfnDllFunc1 = (LPFNDLLFUNC1)GetProcAddress(hDLL,                                           "DLLFunc1");   if (!lpfnDllFunc1)   {      // handle the error      FreeLibrary(hDLL);             return SOME_ERROR_CODE;   }   else   {      // call the function      uReturnVal = lpfnDllFunc1(dwParam1, uParam2);   }}




0 0