vs2017 C++动态链接库的创建和调用(隐式)

一、VS创建动态链接库

1、打开vs新建项目 创建动态链接库

2、添加头文件.h,在h文件中添加如下内容:

#pragma once//该头文件只编译一次
#include<iostream>
#include<vector>
#include<string>
using namespace std;
__declspec(dllexport) int test(int, int);
__declspec(dllexport) bool WindSpeeddataCalc(const vector<int> &rawdata, const float angle, const float Distance, vector<string> &datastr);

3、添加cpp文件(和.h文件名相同),cpp文件中添加一下内容

// data.cpp : 定义 DLL 应用程序的导出函数。
//

#include "stdafx.h"
#include"data.h"
#include<Windows.h>
int test(int a, int b)
{
return a + b;
}
const float PI = 3.14f;
bool WindSpeeddataCalc(const vector<int> &rawdata, const float angle, const float Distance, vector<string> &datastr)
{
int cameradata1 = rawdata[0];
int cameradata2 = rawdata[1];
int cameradata3 = rawdata[2];
int cameradata4 = rawdata[3];
datastr.clear();
if (rawdata[0] != 0 && rawdata[1] != 0)
{
float restructwindspeed12 = sqrt(pow((cameradata1 + cameradata2) / 2 / cos(12.5f*PI / 180), 2) + pow((cameradata1 - cameradata2) / 2 / sin(12.5f*PI / 180), 2));//重构风速12
float angle12 = atan(((cameradata1 - cameradata2) / 2 / sin(12.5f*PI / 180)) / ((cameradata1 + cameradata2) / 2 / cos(12.5f*PI / 180))) * 180 / PI;//角度12
float shear12 = abs((cameradata1 - cameradata2) / Distance);//风切变12
datastr.push_back(std::to_string(restructwindspeed12));
datastr.push_back(std::to_string(angle12));
datastr.push_back(std::to_string(shear12));
}
else
{
for (int i = 0; i < 3; i++)
datastr.push_back("--");
}
if (rawdata[2] != 0 && rawdata[3] != 0)
{
float restructwindspeed34 = sqrt(pow((cameradata3 / cos(25.6f*PI / 180) + cameradata4 / cos(25.6f*PI / 180)) / 2 / cos(12.5f*PI / 180), 2) + pow((cameradata3 / cos(25.6f*PI / 180) - cameradata4 / cos(25.6f*PI / 180)) / 2 / sin(12.5f*PI / 180), 2));//重构风速34
float angle34 = atan(((cameradata4 / cos(25.6f*PI / 180) - cameradata3 / cos(25.6f*PI / 180)) / 2 / sin(12.5f*PI / 180)) / ((cameradata3 / cos(25.6f*PI / 180) + cameradata4 / cos(25.6f*PI / 180)) / 2 / cos(12.5f*PI / 180))) * 180 / PI;//角度34
float shear34 = abs((cameradata4 / cos(25.6f*PI / 180) - cameradata3 / cos(25.6f*PI / 180)) / Distance);//风切变34
datastr.push_back(std::to_string(restructwindspeed34));
datastr.push_back(std::to_string(angle34));
datastr.push_back(std::to_string(shear34));
}
else
{
for (int i = 0; i < 3; i++)
datastr.push_back("--");
}
return true;
}

4、生成解决方案  在debug()目录下即有.dll   .lib等文件

二、VS调用动态链接库

1、创建一个新的项目

2、在头文件夹中引入DLL的.h头文件,把.h 、.lib文件复制到新建项目所在的文件夹,.dll放入新建项目的Debug()目录

3、在资源文件中引入.lib文件

4、在main函数中加入如下代码

#include"data.h"

int main()
{
const float angle = 12.5f;
const float distance = 65.0f;
const vector<int> data= { 1193,983,703,784 };
vector<string> datastr;
bool a=WindSpeeddataCalc(data, angle, distance, datastr);
for (int i = 0; i < datastr.size(); i++)
cout << datastr[i]<<endl;
cout << "result:" << a;
getchar();
return 0;
}

5、项目->属性->配置属性->C/C++->代码生成->运行库,选择多线程调试DLL(/MDd)

猜你喜欢

转载自www.cnblogs.com/tsh292278/p/10432454.html