How to Call Webservice through C++ Dynamic Link Library (DLL) in Visual Studio 2019 Using C++ Rest SDK

 Introduction

DLL is a one of the most useful Windows Components.

In UNIX systems known as shared libraries

DLL is used to share code and resources

It can reduce the size of your applications


Requirements

Windows 7 or Later (Windows 10 Ideal)

Check Desktop Development ith C++ Workload in the Visual Studio Installer


Create Python Flask WebService

Open Pycharm IDE

Create a project with a virtual enviornment

pip install flask

Implement a webservice (Returns a JSON response)

import flask
from flask import request, jsonify

app = flask.Flask(__name__)
app.config["DEBUG"] = True

prediction = {"prediction":
{'id': 0,
'title': 'A Fire Upon the Deep',
'author': 'Vernor Vinge',
'first_sentence': 'The coldsleep itself was dreamless.',
'year_published': '1992'
}
}

# A route to return all of the available entries in our catalog.
@app.route('/api/forex/prediction', methods=['GET'])
def api_all():
return jsonify(prediction)


@app.route('/', methods=['GET'])
def home():
return "<h1>Distant Reading Archive</h1><p>This site is a prototype API for distant reading of science fiction novels.</p>"


app.run()


Create Dynamic Link Library Project


Open Visual Studio 2019 IDE

Click Create a New Project

Select C++, Windows, Library, Select Windows Desktop Wizard




Give Project name, Solution name, Project Location

Project Name :  Calculator


Click Create
Select DLL from the drop down menu

Click OK


Create Calculator.h header file

#pragma once

#ifdef CALCULATOR_EXPORTS
#define CALCULATOR_API __declspec(dllexport)
#else
#define CALCULATOR_API __declspec(dllimport)
#endif



CALCULATOR_API int __stdcall add(int a, int b);



Create Calculator.cpp file

#include "Calculator.h"
#include <cpprest\filestream.h>

int __stdcall add(int a, int b)
{
return a + b;
}

void __stdcall saveResponse()
{
auto fileStream = std::make_shared<Concurrency::streams::ostream>();

// Open stream to output file.
pplx::task<void> requestTask = Concurrency::streams::fstream::open_ostream(U("prediction.json"))

// Make a GET request.
.then([=](Concurrency::streams::ostream outFile) {
*fileStream = outFile;

// Create http_client to send the request.
http_client client(U("http://127.0.0.1:5000"));

// Build request URI and start the request.
return client.request(methods::GET, uri_builder(U("api")).append_path(U("forex")).append_path(U("prediction")).to_string());
})

// Get the response.
.then([=](http_response response) {
// Check the status code.
if (response.status_code() != 200) {
throw std::runtime_error("Returned " + std::to_string(response.status_code()));
}

// Write the response body to file stream.
response.body().read_to_end(fileStream->streambuf()).wait();

// Close the file.
return fileStream->close();
});

// Wait for the concurrent tasks to finish.
try {
while (!requestTask.is_done()) { std::cout << "."; }
}
catch (const std::exception& e) {
printf("Error exception:%s\n", e.what());
}
}


Copy  cpprestsdk (built for X64) in the same Folder which this Calculator Project exists
Right click on the project & Select Properties
C/C++ -> General 
Set Additional Include Directories
..\..\cpprestsdk\Release\include



Place  cpprest142_2_10d.lib in the project Directory


Linker -> Input
Set Additional Dependencies

$(ProjectDir)cpprest142_2_10d.lib



Right Click on the calculator DLL project & Build





Calculator.dll is created on the Calculator\x64\Debug\ folder


Create Client Console Project to use the DLL (DLL uses cpprestsdk)

Open Visual Studio 2019 IDE

Click Create a New Project

Select C++, Windows, Library, Select Console App




Give Project name, Solution name, Project Location

Project Name :  CalculatorClient



Click Create

#include <iostream>
#include "Calculator.h"


int main()
{
    int result= add(5, 5);
    cout << result << endl;
    saveResponse();
    std::cin;
}

Right click on the project & Select Properties
C/C++ -> General 
Set Additional Include Directories - Set relevant header file folders (dll headers, cpprestsdk headers)
..\..\Calculator\Calculator
..\..\cpprestsdk\Release\include



Linker -> Additional Library Directories




Linker -> Input

Copy cpprest142_2_10d.dll to the CalculatorClient\x64\Debug folder

Build Event - > Post-Build Event
Command Line
xcopy /y /d "..\..\Calculator\$(IntDir)Calculator.dll" "$(OutDir)"

Run the WebService





Right Click on CalculatorClient Project , Click Build (Build is a must , because only after the build it copies the dll from DLL library project)

Right Click on CalculatorClient Project , Click Debug


You can see server is hit with the client request



Projects Source Code





Comments

Popular posts from this blog

How to build CppRestSDK using Vcpkg in Visual Studio 2019 (X64 windows & X86 windows)

Implementing ResNet with Base Line Accuracy