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未拷至相应目录下

转载于:https://www.cnblogs.com/dahai/archive/2011/06/14/2080693.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值