dll动态链接库导出函数方法 -- 静态导出(__declspec前缀导出)
简介
在之前已经笔者已经写过利用.def文件进行dll函数动态导出的文章,那么今天就给大家介绍一下,如何利用__declspec函数前缀进行简单的静态函数导出。
要点
大家阅读过动态导出的文章后,只需要将原文导出函数的前缀加上extern"C" __declspec(dllexport)前缀,然后删除原项目中的.def文件即可。
附上DLL源码与测试源码
- dll源码
 
// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include "stdafx.h"
BOOL APIENTRY DllMain(HMODULE hModule,
	DWORD  ul_reason_for_call,
	LPVOID lpReserved
)
{
	switch (ul_reason_for_call)
	{
	case DLL_PROCESS_ATTACH:
	case DLL_THREAD_ATTACH:
	case DLL_THREAD_DETACH:
	case DLL_PROCESS_DETACH:
		break;
	}
	return TRUE;
}
extern"C" __declspec(dllexport) int ShowMessageBox(const WCHAR* lpText, const WCHAR* lpCaption)
{
	MessageBox(NULL, lpText, lpCaption, 0);
	return 0;
}
- 测试源码
 
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <Windows.h>
using namespace std;
typedef int(*ShowMessageBox)(const WCHAR* lpText, const WCHAR* lpCaption);   //声明函数指针,告诉程序从动态链接库导入的地址是什么类型的函数
int main(void)
{
	HMODULE hm = LoadLibrary("DemoDLL.dll");			//加载动态链接库
	if (hm == NULL)
	{
		printf("Library Error !\n");
		system("pause");
		return 0;
	}
	ShowMessageBox SMessageBox = (ShowMessageBox)GetProcAddress(hm, "ShowMessageBox");   //查找函数地址
	if (SMessageBox == NULL)
	{
		cout << GetLastError() << endl;
		printf("GetProcAddress error \n");
		system("pause");
		return 0;
	}
	SMessageBox(L"HelloWorld", L"Tip");			//使用dll中导出的函数
	FreeLibrary(hm);
	return 0;
}
测试截图

    本文为博主总结文章,欢迎转载,请注明出处。

                
            
        
浙公网安备 33010602011771号