动态链接库DLL导出函数并导入使用

动态链接库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) == )
{
printf("cimId无值!");
return false;
} if (strcmp(cimId, "aaaaaa") == )
{
result = "";
}
else if (strcmp(cimId, "bbbbbb"))
{
result = "";
} *scadaId = result;
printf("fun scadaId: %s \n", *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(, );
char* cimId = "aaaaaa";
char* scadaId = "";
bool b = cim2scada(cimId, &scadaId); printf("Max结果为%d\n", a);
printf("cimId:%s, scadaId:%s\n", cimId, scadaId); FreeLibrary(HDLL); // 卸载MyDll.dll文件
}

编译生成Debug文件夹,讲之前生成的Dll文件拷贝到该Debug文件夹中,然后运行该测试样例。

动态链接库DLL导出函数并导入使用

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++类、对象,并进行导入使用。

上一篇:C++类的成员函数(在类外定义成员函数、inline成员函数)


下一篇:Windows环境下python多版本配置方案