动态库导出类-----practice

本文介绍如何在DLL中导出类及静态成员变量,并演示了如何在客户端正确使用这些导出的元素。同时,解释了__declspec(dllexport)与__declspec(dllimport)的区别及其在DLL编程中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建dll;

// "MyDll.h"

#include <stdio.h>
#include <stdlib.h>
#include "Public.h"

#define DLL_EXPORT __declspec(dllexport)
class DLL_EXPORT SimpleDLLClass
{
public:
	SimpleDLLClass();
	virtual ~SimpleDLLClass();
	virtual int getValue() { return m_nValue;};

private:
	int m_nValue;
};

//MyDll.cpp

#include "MyDll.h"

SimpleDLLClass::SimpleDLLClass()
{
	m_nValue = 9;
}

SimpleDLLClass::~SimpleDLLClass()
{
}

编译生成MyDll.lib和MyDll.dll

1. 静态调用

#include <stdio.h>
#include <stdlib.h>
#include "Public.h"

#define DLL_EXPORT __declspec(dllexport)	//调用头文件
class DLL_EXPORT SimpleDLLClass
{
public:
	SimpleDLLClass();
	virtual ~SimpleDLLClass();
	virtual int getValue() { return m_nValue;};

private:
	int m_nValue;
};
包含MyDll.h 头文件,对类进行声明定义。
然后就可以当使用本地类使用。

int _tmain(int argc, _TCHAR* argv[])
{
	SimpleDLLClass spCls;
	wcout<<spCls.getValue()<<endl;
}

若 在"MyDll.h"中,将类的成员变量int m_nValue; 修改成static。 再用1. 静态调用方法就会找不到m_nValue;原因(原因:静态变量m_nValue已被DLL导出,但SimpleDLLClass无法访问m_nValue) 

 将调用头文件 #define DLL_EXPORT __declspec(dllexport)修改成 :

#define DLL_EXPORT __declspec(dllimport) 解决。

dllimport是为了更好的处理类中的静态成员变量(或者其他...)的,如果没有静态成员变量(或者其他...),那么这个__declspec(dllimport)无所谓.

动态加载(待补充)....

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值