C++ 实践之动态库完整实现

C++动态库封装实践
本文分享了使用C++进行动态库(DLL)封装的过程,包括动态库的创建、使用及测试程序的编写。通过具体代码示例展示了如何读取INI配置文件。

    这几日来一直在鼓得C++终于有些成果。下面就把这一段时间的努力分享一下。首先动态库文件代码如下:

    study_dll:

    common.h 头文件:

    

#ifndef DLL
	#define DLL



	extern "C" int __stdcall readIniFile(char* lable, char* anchor,  char* contentValue);
#endif


    common.cpp 主文件:

#include <iostream>

#include <string.h>

#include <windows.h>


using namespace std;

#define INI_FILE_PATH "./study.ini"
#define LOG_VALUE_MAXSIZE 80

int readIniFile(char* lable, char* anchor,  char* contentValue) {

	char buffer[LOG_VALUE_MAXSIZE];
	GetPrivateProfileString(lable, anchor, NULL, buffer, sizeof(buffer), INI_FILE_PATH );//读取 配置文件 需要引入 <windows.h>

	strcpy(contentValue, buffer);

	//cout << contentValue;
	
	return 0;


}

common.def 文件

LIBRARY common
EXPORTS
readIniFile @ 1

在成功生成动态库文件后,将study.dll文件拷贝到测试程序根目录。

 C++测试程序如下:

 

#include <iostream>

#include <string.h>

#include <windows.h>


using namespace std;





typedef void(*Dllfun)(char* , char*, char*);

int main() {
	cout << "************************************" << "\n";
	cout << "这是 study 项目" << "\n";
	cout << "************************************" << "\n";

	
	cout << "************************************" << "\n";
	cout << "这是 调用study.dll  readIniFile方法运行" << "\n";
	Dllfun read;
	HINSTANCE hdll;
	hdll=LoadLibrary("study_dll.dll");
	if(hdll==NULL){
		FreeLibrary(hdll);
	}
	read=(Dllfun)GetProcAddress(hdll,"readIniFile");
	if(read==NULL){
		FreeLibrary(hdll);
		cout<<"read is null";
	}else{
		
	}
	char* lable = "Log";
	char* anchor = "Level";
	char* iniValue1 = (char*)malloc(80);

	try{
		read(lable, anchor, iniValue1);
	}
	catch(exception  *ex){
		cout<<ex;
	}
	
	
	cout << "************************************" << "\n";


	return 0;
}

 

完美输出对应结果。下一步尝试引入对象、结构体 进行 动态库 封装。

转载于:https://my.oschina.net/u/3435444/blog/1505436

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值