动态链接库DLL导出函数并导入使用
本文完全参考自《vs2008制作dll笔记,回带值样例》。
首先制作DLL文件,在vs2010中新建Win32控制台项目,选择DLL选项,简历头文件,源文件如下:
头文件:
// MyDll.h extern "C" _declspec(dllexport) int Max(int a, int b); extern "C" _declspec(dllexport) int Min(int a, int b); extern "C" _declspec(dllexport) bool cim2scada(char* cimId, char** scadaId);
源文件:
// MyDll.cpp : Defines the exported functions for the DLL application. // #include "MyDll.h" #include <iostream> int Max(int a, int b) { if (a >= b) { return a; } else { return b; } } int Min(int a, int b) { if (a >= b) { return b; } else { return a; } } bool cim2scada(char* cimId, char** scadaId) { char* result; if (cimId == NULL) { printf("空指针!"); return false; } else if (strlen(cimId) == 0) { printf("cimId无值!"); return false; } if (strcmp(cimId, "aaaaaa") == 0) { result = "1000"; } else if (strcmp(cimId, "bbbbbb")) { result = "2000"; } *scadaId = result; printf("fun scadaId: %s ", *scadaId); return true; }
然后,创建测试样例,重新简历Win32控制台程序,选择控制台选项,建立测试代码:
#include "windows.h" #include <iostream> int main() { typedef int (*pMax)(int a, int b); typedef int (*pMin)(int a, int b); typedef bool (*pcim2scada)(char* cimid, char** scada); HINSTANCE HDLL; HDLL = LoadLibrary(L"MyDll.dll"); // 加载动态链接库MyDll.dll文件; pMax Max = (pMax)GetProcAddress(HDLL, "Max"); pMin Min = (pMin)GetProcAddress(HDLL, "Min"); pcim2scada cim2scada = (pcim2scada)GetProcAddress(HDLL, "cim2scada"); int a = Max(5, 12); char* cimId = "aaaaaa"; char* scadaId = ""; bool b = cim2scada(cimId, &scadaId); printf("Max结果为%d ", a); printf("cimId:%s, scadaId:%s ", cimId, scadaId); FreeLibrary(HDLL); // 卸载MyDll.dll文件 }
编译生成Debug文件夹,讲之前生成的Dll文件拷贝到该Debug文件夹中,然后运行该测试样例。
DLL导出并导入生成函数需要注意几点:
extern "C" _declspec(dllexport)
typedef int (*pMax)(int a, int b);
typedef int (*pMin)(int a, int b);
typedef bool (*pcim2scada)(char* cimid, char** scada);
HINSTANCE HDLL;
HDLL = LoadLibrary(L"MyDll.dll"); // 加载动态链接库MyDll.dll文件;
pMax Max = (pMax)GetProcAddress(HDLL, "Max");
pMin Min = (pMin)GetProcAddress(HDLL, "Min");
pcim2scada cim2scada = (pcim2scada)GetProcAddress(HDLL, "cim2scada");
接下来,将学习如何用DLL导出C++类、对象,并进行导入使用。