这几日来一直在鼓得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;
}
完美输出对应结果。下一步尝试引入对象、结构体 进行 动态库 封装。