• DLL简单示例


    DLL调用方式:

    1. 静态调用(编译时链接DLL)
    2. 动态调用(运行时显示调用)

    代码如下:

    • DLL
      • DLL的编译将生成DLLLIB两个文档(TestDLL.dll、TestDLL.lib)。
      • LIB文档是在编译时用来链接DLL的,称为引用链接库
    #include <windows.h>
    
    // Export this function
    extern "C" __declspec(dllexport) double AddNumbers(double a, double b);
    
    // DLL initialization function
    BOOL APIENTRY
    DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
    {
    	return TRUE;
    }
    
    // Function that adds two numbers
    double
    AddNumbers(double a, double b)
    {
    	return a + b;
    }
    • 静态调用
      • TestDLL.lib拷至编译目录下
      • TestDLL.dll拷至exe目录下
    #include <windows.h>
    #include <stdio.h>
    #pragma comment(lib,"TestDLL.lib") //链接引用链接库
    
    // Import function that adds two numbers
    extern "C" __declspec(dllimport)double AddNumbers(double a, double b);
    
    int
    main(int argc, char **argv)
    {
    	double result = AddNumbers(1, 2);
    	printf("The result was: %f\n", result);
    
    	system("pause");
    	return 0;
    }
    • 动态调用
      • TestDLL.dll拷至exe目录下
      • 无需TestDLL.lib
    #include <windows.h>
    #include <stdio.h>
    
    // DLL function signature
    typedef double (*importFunction)(double, double);
    
    int
    main(int argc, char **argv)
    {
    	importFunction addNumbers;
    	double result;
    
    	// Load DLL file
    	HINSTANCE hinstLib = LoadLibrary(L"TestDLL.dll");
    	if (hinstLib == NULL) {
    		printf("ERROR: unable to load DLL\n");
    		return 1;
    	}
    
    	// Get function pointer
    	addNumbers = (importFunction)GetProcAddress(hinstLib, "AddNumbers");
    	if (addNumbers == NULL) {
    		printf("ERROR: unable to find DLL function\n");
    		return 1;
    	}
    
    	// Call function.
    	result = addNumbers(1, 2);
    
    	// Unload DLL file
    	FreeLibrary(hinstLib);
    
    	// Display result
    	printf("The result was: %f\n", result);
    
    	system("pause");
    	return 0;
    }
    • 动态调用失败原因:
      1. 调用约定不匹
      2. 导出函数名被修改(可通过Depends.Exe查看导出函数名)
      3. 相应LIB或DLL未拷至相应目录下
  • 相关阅读:
    实验2(第二章课后习题)
    weekend及反位数(第一次c++作业)
    如何在Vue项目中使用百度地图
    Vue中使用js-pinyin包实现城市按首字母排序
    Webstorm中使用less编写css
    关于cookie的使用
    Vue数据双向绑定的实现
    Vue的生命周期
    Vue-cli(Vue脚手架)挂载Element-ui和axios方法
    Vue脚手架学习笔记(一)
  • 原文地址:https://www.cnblogs.com/dahai/p/2080693.html
Copyright © 2020-2023  润新知