1.
新建DLL工程
MFC DLL --> 创建规则 DLL --> 带静态链接 MFC 的规则 DLL
编译生成 .lib .dll 文件
完整.h文件代码
1 // testMfcDll.h : testMfcDll DLL 的主头文件
2 //
3
4 #pragma once
5
6 #ifndef __AFXWIN_H__
7 #error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件"
8 #endif
9
10 #include "resource.h" // 主符号
11
12
13 // CtestMfcDllApp
14 // 有关此类实现的信息,请参阅 testMfcDll.cpp
15 //
16
17 class CtestMfcDllApp : public CWinApp
18 {
19 public:
20 CtestMfcDllApp();
21
22 // 重写
23 public:
24 virtual BOOL InitInstance();
25
26 DECLARE_MESSAGE_MAP()
27 };
28
29 class __declspec(dllexport) testMfcDll;
30 class testMfcDll
31 {
32 public:
33 testMfcDll(){};
34 virtual ~testMfcDll(){};
35 void sayHello();
36 CString &sayHelloWord();
37 void sayWhat(CString &);
38
39 CString strHello;
40 };
完成.cpp 文件代码
1 // testMfcDll2.cpp : 定义 DLL 的初始化例程。
2 //
3
4 #include "stdafx.h"
5 #include "testMfcDll2.h"
6
7 #ifdef _DEBUG
8 #define new DEBUG_NEW
9 #endif
10
11 //
12 //TODO: 如果此 DLL 相对于 MFC DLL 是动态链接的,
13 // 则从此 DLL 导出的任何调入
14 // MFC 的函数必须将 AFX_MANAGE_STATE 宏添加到
15 // 该函数的最前面。
16 //
17 // 例如:
18 //
19 // extern "C" BOOL PASCAL EXPORT ExportedFunction()
20 // {
21 // AFX_MANAGE_STATE(AfxGetStaticModuleState());
22 // // 此处为普通函数体
23 // }
24 //
25 // 此宏先于任何 MFC 调用
26 // 出现在每个函数中十分重要。这意味着
27 // 它必须作为函数中的第一个语句
28 // 出现,甚至先于所有对象变量声明,
29 // 这是因为它们的构造函数可能生成 MFC
30 // DLL 调用。
31 //
32 // 有关其他详细信息,
33 // 请参阅 MFC 技术说明 33 和 58。
34 //
35
36 // CtestMfcDll2App
37
38 BEGIN_MESSAGE_MAP(CtestMfcDllApp, CWinApp)
39 END_MESSAGE_MAP()
40
41
42 // CtestMfcDll2App 构造
43
44 CtestMfcDllApp::CtestMfcDllApp()
45 {
46 // TODO: 在此处添加构造代码,
47 // 将所有重要的初始化放置在 InitInstance 中
48 }
49
50
51 // 唯一的一个 CtestMfcDll2App 对象
52
53 CtestMfcDllApp theApp;
54
55
56 // CtestMfcDll2App 初始化
57
58 BOOL CtestMfcDllApp::InitInstance()
59 {
60 CWinApp::InitInstance();
61
62 return TRUE;
63 }
64
65
66 void testMfcDll::sayHello()
67 {
68 //这是win的MessageBox
69 MessageBox(NULL, _T("hello"), _T("提示"), MB_OK);
70 }
71
72
73 CString& testMfcDll::sayHelloWord()
74 {
75 strHello = _T("hello world");
76 return strHello;
77 }
78
79
80 void testMfcDll::sayWhat(CString &str)
81 {
82 if(str == _T("hello"))
83 {
84 str = _T("get way");
85 MessageBox(NULL, _T("get way"), _T("提示"), MB_OK);
86 }else
87 {
88 MessageBox(NULL, _T("hello"), _T("提示"), MB_OK);
89 }
90 }
2.
新建 MFC 对话框程序调用 DLL
MFC 应用程序 --> 基于对话框 在静态中使用 MFC -->其他选项都是默认
把 DLL 的 .h 文件加入到项目,把编译生成的 .lib 文件加入到项目资源
在对话框程序中增加一个按钮,在按钮的点击消息实现函数中增加代码
1 testMfcDll test;
2 test.sayHello();// hello
3 CString str = _T("hello");
4 str = test.sayHelloWord();
5 test.sayWhat(str);// hello
6 MessageBox(str);// hello world
3.
参考
MFC扩展DLL,函数参数或返回值中有&,调用时报无法解析的外部符号
MFC DLL 选择静态 MFC时,调用的程序也使用“在静态中使用 MFC”
MFC DLL 选择共享 MFC时,调用的程序也使用“在共享中使用 MFC”
MFC 扩展 DLL 使用一些特殊参数例如&,调用时会出现“无法解析的外部符号”,这是静态mfc动态mfc不对应的问题
例如上述例子中 DLL 使用 MFC 扩展 DLL 选项时,只能调用第一个函数,其他2个函数都提示 “无法解析的外部符号”