封装dll动态链接库
1.打开vs,创建一个动态链接库(DLL)或者具有导出项的(DLL)动态链接库
2.创建成功后会出现一下文件(本人创建的是动态链接库)
3.创建一个.h与.cpp文件,内容如下:
read.h
#pragma once
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
#ifdef __cplusplus // if used by C++ code
extern "C" { // we need to export the C interface
#endif
#ifdef DLL_TRAINING_API
#else
#define DLL_TRAINING_API _declspec(dllimport) //当编译时,头文件不参加编译,所以.cpp文件中先定义,后头文件被包含进来,因此外部使用时,为dllexport,而在内部编译时,则为dllimport
//区域结构体
struct Small_area
{
int A1_large_area_means_lens; //A1小区域数组大小
int apply_size;//涂抹大小
};
struct Array
{
vector<int> A1_large_area_means; //A1的小区域平均灰度
};
extern Small_area DLL_TRAINING_API small_area;
extern Array DLL_TRAINING_API arr;
extern string DLL_TRAINING_API configuration_file_path; //cfg的二进制配置文件
void DLL_TRAINING_API write_cfg(string file_path); //写二进制文件
void DLL_TRAINING_API read_cfg(); //读二进制文件
}
#endif
read.cpp
#include "pch.h"
#include "read.h"
#define DLL_TRAINING_API _declspec(dllexport)
Small_area DLL_TRAINING_API small_area;
Array DLL_TRAINING_API arr;
string DLL_TRAINING_API configuration_file_path;
string DLL_TRAINING_API ini_path = "D:/cudaHygiene/image/1.ini";
void DLL_TRAINING_API read_cfg()
{
ifstream f(configuration_file_path, ios_base::in | ios_base::binary);
if (!f)
{
cout << "读取文件失败!" << " read_cfg" << endl;
return;
}
int lens = 0;//字符数
f.read((char*)&small_area, sizeof(small_area));
lens += sizeof(small_area);
f.seekg(lens, ios::beg);
//A1的小区域平均灰度
arr.A1_large_area_means.resize(small_area.A1_large_area_means_lens);
f.read((char*)(arr.A1_large_area_means.data()), arr.A1_large_area_means.size() * sizeof(arr.A1_large_area_means.front()));
cout << "已读取完毕!" << endl;
f.close();
}
void DLL_TRAINING_API write_cfg(string file_path)
{
//写出数据
ofstream f(file_path, ios_base::out | ios_base::binary);
if (!f)
{
cout << "创建文件失败" << endl;
return;
}
//A1小区域
f.write((char*)&small_area, sizeof(small_area));
//A1的小区域平均灰度
f.write(reinterpret_cast<char*>(arr.A1_large_area_means.data()), arr.A1_large_area_means.size() * sizeof(arr.A1_large_area_means.front()));
cout << "已写完!<< endl";
f.close();
}
4.点击生成解决方案,就会生成.dll与.lib文件(注意:如果点击本地调试器,因为没有主函数会报错)
调用dll动态链接库
1.创建一个空项目, 写一个空的主函数,生成Debug或者Release文件夹
2.将生成的dll与lib放入生成的文件中
3.将.h文件放入创建的项目的代码目录
4.调用dll
#include "read.h"
#pragma comment(lib,"D:\\C\\Project5\\x64\\Debug\\read.lib")
void main()
{
configuration_file_path = "D:/C/cudaHygiene/image/0.cfg";
read();
cout << configuration_file_path << endl;
}