写一个简单的动态库并调用

动态库分为静态调用和动态调用。

话不多说,以下来介绍一个简单的动态库的实现及调用。

先写一个动态库,我这里用的是Win32来写的一个简单的动态库。创建时选择DLL,完成之后在.CPP文件中写下函数的实现,然后在.h文件中声明导出文件。生成文件后,会在Debug文件夹下生成.dll文件和.lib文件,这就是我们所要的东西。

.h文件:

#ifdef WIN32PROJECT2_EXPORTS
#define WIN32PROJECT2_API __declspec(dllexport)
#else
#define WIN32PROJECT2_API __declspec(dllimport)
#endif

// 此类是从 Win32Project2.dll 导出的
class WIN32PROJECT2_API CWin32Project2 {
public:
	CWin32Project2(void);
	// TODO:  在此添加您的方法。
};

extern WIN32PROJECT2_API int nWin32Project2;

WIN32PROJECT2_API int fnWin32Project2(void);

EXTERN_C  WIN32PROJECT2_API int Add(int a, int b);

.cpp文件:

#include "stdafx.h"
#include "Win32Project2.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// 唯一的应用程序对象

CWinApp theApp;

using namespace std;

WIN32PROJECT2_API int Add(int a, int b)
{
	return a + b;
}

接下来就是调用动态库了!!!

我这里用的是MFC调用动态库,创建一个MFC应用程序,选择基本对话框,然后在其控制面板上添加一个按钮BUTTON1,双击进去。然后在其中写程序调用刚才生成的动态库。在此之前,要先将之前生成的.dll文件和.lib文件放在你的MFC文件下。

代码如下:

//动态调用
typedef int(*add)(int a, int b); //宏定义函数指针类型
void CMFCApplication2Dlg::OnBnClickedButton1()
{
		HINSTANCE mDll; //动态调用
		add fun = NULL; //函数指针

		mDll = LoadLibrary(L"..\\Win32Project2.dll");  //获取路径

		if (mDll != NULL)
		{
			fun = (add)GetProcAddress(mDll, "Add");  //获取库函数
			if (fun != NULL)
			{
				int ret = fun(1, 2);
				char strRes[100] = { 0 };
				sprintf_s(strRes, "和为%d", ret);
				MessageBoxA(NULL, strRes, NULL, 0);
			}
			else
			{
				MessageBoxA(NULL, "error", NULL, 0);
			}
			FreeLibrary(mDll);    //卸载动态库
		}
}


//静态调用
#pragma  comment(lib,"Win32Project2.lib")
EXTERN_C  int __declspec(dllexport)  Add(int a, int b);
void CMFCApplication2Dlg::OnBnClickedButton2()
{
	
	int count = Add(1, 9);
	char strRes[100] = { 0 };
	sprintf_s(strRes, "和为%d", count);
	MessageBoxA(NULL, strRes, NULL, 0);

	// TODO: 在此添加控件通知处理程序代码
}

这就是一个最简单的动态库的实现与调用。

发布了36 篇原创文章 · 获赞 6 · 访问量 2046

猜你喜欢

转载自blog.csdn.net/the_sea1/article/details/100098021
今日推荐