C和C++编写、调用动态链接库的方法

本文包括以下内容:

1. 如何编译生成dll和lib文件

2. 如何在外部程序调用dll(动态链接)并访问其函数

3. 如何在外部程序调用lib(静态链接)并访问其函数


一、如何编译生成dll和lib文件

1. 新建Win32控制台程序,勾选dll

2. 新建mydll.h文件,写入代码:

#ifndef _CLASS_H_
#define _CLASS_H_

//declaration
extern "C" __declspec(dllexport) int  add(int a ,int b);

#endif

3. mydll.cpp文件,写入代码:

#include "stdafx.h"
#include "ClassDLL.h"

//implement
__declspec(dllexport) int add(int a ,int b)
{
	return a+b;
}

二、外部调用dll

#include "stdafx.h"
#include <Windows.h>
#include <iostream>
using namespace std;

/*dynamic call*/
typedef int(*lpAddFun)(int, int);

int _tmain(int argc, _TCHAR* argv[])
{
	/*  dynamic call  */
	HINSTANCE hDll;
	lpAddFun addFun;
	hDll = LoadLibrary(L"E:/ClassDLL.dll");
	if (hDll != NULL)
	{
		addFun = (lpAddFun)GetProcAddress(hDll, "add");
		if (addFun != NULL)
		{
			int result = addFun(2, 3);
			cout<<result;
		}
		FreeLibrary(hDll);

	}

	return 0;
}

三、外部调用lib

#include "stdafx.h"
#include "DoorFSM.h"
#include <Windows.h>
#include <iostream>
using namespace std;

/*static call*/
#pragma comment(lib,"D:/ClassDLL.lib")
extern "C" __declspec(dllimport) int add(int x,int y);

int _tmain(int argc, _TCHAR* argv[])
{
	/* static call */
	int result = add(2,3);
	cout<<result<<endl;

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值