2017.04.13 有关动态链接库的学习

    xiaoxiao2021-04-14  74

    第一步:在vs中新建一个win32项目的DLL工程,工程名字取为a1

    在dllmain.cpp文件下添加如下代码

    #include "stdafx.h" #include<Windows.h> #include <iostream> using namespace std; _declspec(dllexport) int add(int a,int b) { return a+b; } _declspec(dllexport) int sub(int a,int b) { return a-b; } BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: cout<<"这是我的第一个动态链接库"<<endl; break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }

    然后,重新生成解决方案,即可在a1文件夹下的debug文件下找到a1.dll与a1.lib程序

    2.第二步

    重新建立一个win32控制台应用程序工程,取名a2

    (1)隐式加载动态链接库,将上述a1工程中debug目录下的a1.dll与a1.lib复制粘贴到本工程a2中。

    在a2工程中的a2.cpp中添加如下代码,编译运行即可

    #include "stdafx.h" #include <iostream> using namespace std; #include <windows.h> #pragma comment(lib,"a1.lib"); _declspec(dllimport) int add(int ,int); _declspec(dllimport) int sub(int ,int); int _tmain(int argc, _TCHAR* argv[]) {     cout<<"5+3="<<add(5,3)<<endl;     cout<<"5-3="<<sub(5,3)<<endl;     return 0; }

    (2)显式加载动态链接库,将上述a1工程中debug目录下的a1.dll 复制到本工程a2目录下。注意,只需要 a1.dll,不需要 a1.lib。

    在a2工程中的a2.cpp中添加如下代码,编译运行即可

    (一般采用显式加载动态链接库。参考资料:参考资料1  参考资料2   参考资料3)

    #include "stdafx.h" #include <iostream> using namespace std; #include<windows.h> // 必须包含 windows.h typedef int (*FUNADDR)(int,int); // 指向函数的指针 int main() {   int a=10, b=5;   HINSTANCE dllDemo = LoadLibrary("dllDemo.dll"); FUNADDR add, sub; if(dllDemo) { add = (FUNADDR)GetProcAddress(dllDemo, "add"); sub = (FUNADDR)GetProcAddress(dllDemo, "sub"); } else { printf("Fail to load DLL!\n");   system("pause"); exit(1); } printf("a+b=%d\n", add(a, b)); printf("a-b=%d\n", sub(a, b)); system("pause"); return 0; }

    转载请注明原文地址: https://ju.6miu.com/read-669861.html

    最新回复(0)