现在的位置: 首页 > 综合 > 正文

C++创建动态链接库示例

2013年04月10日 ⁄ 综合 ⁄ 共 1602字 ⁄ 字号 评论关闭
文章目录

一:生成DLL的方法

首先在VS2010下创建win32控制台工程, 创建DLL项目,空项目,创建以下两个文件

Add.h

#ifdef MYLIBAPI
#else
#define MYLIBAPI extern "C" __declspec(dllimport)
#endif 

MYLIBAPI int g_nResult;

MYLIBAPI int Add(int a, int b);

Add.cpp

#include <Windows.h>

#define MYLIBAPI extern "C" __declspec(dllexport)

#include "Add.h"

int g_nResult;

int Add(int a, int b)
{
	g_nResult = a + b;

	return g_nResult;
}

编辑在工程目录下生产了一个lib还有一个dll

二:使用DLL的方法

两种方法

(1)隐式链接

         需要的文件有Add.h, Add.lib,同时工程目录下应该有Add.dll,否则会提示你寻找Add.dll,(Add.dll的默认寻找路径)

示例代码如下:

#include <iostream>
#include <Windows.h>
#include "Add.h"

using namespace std;

int main()
{
	cout<<Add(1,2)<<endl;

	system("pause");
	return 0;
}

(2)显示链接

        需要Add.dll, 在函数中需要调用LoadLibrary和FreeLibrary

示例代码如下:

#include <iostream>
#include <stdio.h>
#include <string>
#include <Windows.h>
using namespace std;

typedef int (*DLLFUNC) (int, int);

int main()
{
	DLLFUNC dllfunc;
	bool fRunTimeLinkSuccess = false;
	
	HINSTANCE hInstLib = LoadLibrary(TEXT("TestAdd.dll"));
	if(NULL != hInstLib)
	{
		dllfunc = (DLLFUNC)GetProcAddress(hInstLib, "Add");
		if(NULL != dllfunc)
		{
			fRunTimeLinkSuccess = true;
			cout<<dllfunc(1,2)<<endl;
		}
		FreeLibrary(hInstLib);
	}
	if(!fRunTimeLinkSuccess)
	{
		cout<<"Message printed from executable"<<endl;
	}
		
	system("pause");
	return 0;
}

注释:

The directory from which the application loaded.
The system directory. Use the GetSystemDirectory function to get the path of this directory. (system32目录) 
The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched. (System目录) 
The Windows directory. Use the GetWindowsDirectory function to get the path of this directory. (Windows目录) 
The current directory.
The directories that are listed in the PATH environment variable. Note that this does not include the per-application path specified by the App Paths registry key.

抱歉!评论已关闭.