Run Python in C ++ on Visual Studio 2017

background

At work (), I want to run Python in C ++, and now I have to. At that time, it took a lot of time to build the environment, so I would like to summarize it once. Install some. It also takes time.

Development environment

·laptop ・ OS: window 10 64 bit ・ CPU: Heppoko ・ GPU: None ・ Visual Studio 2017 ・ C ++ -Python 3.7.4

Installation contents

・ Visual Studio 2017 -Python 3.7.4 ・ Boost 1.70.0

Installation: Visual Studio 2017

Go to the URL below and download "** Download Community 2017 **". This can be used free of charge for individuals. We also recommend that you create a Microsoft account. It is said that if you use it for about a month, you will not be able to use it unless you create an account and log in (fear).

URL


https://docs.microsoft.com/ja-jp/visualstudio/releasenotes/vs2017-relnotes

image.png

Then install it. Check "** Desktop development with C ++ " on the left side and " WINDOWS 10 SDK ** on the right side" respectively. ** Python can't be included here **. This time I will put in genuine Python. You can add Python (or anaconda) by Visual studio 2017, I'm afraid to make Python dependent on Visual studio 2017 personally, so Build the environment so that they are independent of each other.

image.png

The installation will start as shown below. image.png

Installation: Python 3.7.4

You can check how to install Python on many sites, but I will post it for confirmation.

URL


https://www.python.org/downloads/release/python-374/

Scroll down the URL and you will find Files. Since the OS is windosn 64bit, download ** windos x86-64 executable installer **.

image.png

Check Add Python 3.7 to PATH and pass the environment variable path in your PC.

image.png

Installation: boost 1.70.0

Download from the following URL.

URL


https://www.boost.org/users/history/version_1_70_0.html

boost also has a library element that connects C ++ and Python. There is also the latest version, but I have confirmed that 1.70.0 can be used before, so I specified this this time.

image.png

Download it, unzip it, and place it directly under your C drive. ** Please note that setting boost takes a considerable amount of time. ** ** It takes a terrifying amount of time. So wait patiently when working with files. I'm taking 30 minutes to unzip the zip file. Note the location of the directory.

image.png

Then install boost at the command prompt (cmd). ○○ is the user name.

cmd


C:\Users\○○ > cd C:\boost_1_70_0
C:\boost_1_70_0>bootstrap.bat

Execution result of bootstrap.bat.

cmd


Building Boost.Build engine

Generating Boost.Build configuration in project-config.jam for msvc...

Bootstrapping is done. To build, run:

    .\b2

To adjust configuration, edit 'project-config.jam'.
Further information:

    - Command line help:
    .\b2 --help

    - Getting started guide:
    http://boost.org/more/getting_started/windows.html

    - Boost.Build documentation:
    http://www.boost.org/build/

I installed Visual Studio 2017 in 1. Pay attention to each version when installing boost. · Visual Studio 2017 is mscv-14.1 -64bit x64 Also, install boost by typing the following without moving the directory.

cmd


b2.exe toolset=msvc-14.1 link=static runtime-link=static,shared --build-dir=build/x64 address-model=64 -j5 install --includedir=C:\boost_1_70_0\include --libdir=C:\boost_1_70_0\stage\lib\x64

Execution of sample program

I'm ready. It may have taken some time to boost, but let's keep going (sweat).

Create a new project

Launch Visual Studio 2017 and launch a new project. Select a console app in C ++. The project name this time is test_Cplus2_Python. image.png

Set project properties

Right-click on the project and select Properties. There are four setting items.

  1. Change the solution configuration and solution platform. Set on both the property page and the main screen. It's easy to forget to change this setting.
  2. Include boost and Python.
  3. Set to multithreading.
  4. Link boost and Python .lib files.

Property page settings


1.Solution configuration and solution platform
Changed from Debug to Release
x86 → x64

2. C++→ General → Additional include
C:\boost_1_70_0
C:\Users\○○\AppData\Local\Programs\Python\Python37\include

3. C++→ Code generation → With runtime library
Multithread(/Change to MT)

4.Linker → General → Additional library directory
C:\boost_1_70_0\stage\lib\x64
C:\Users\○○\AppData\Local\Programs\Python\Python37\libs

The setting items are surrounded by a red outer frame. ○○ is the user name. image.png

Run only once

Once you have set the project properties, run the program once. By executing it, you can confirm that the project works and create an .exe file. It's okay if Hello world! Appears.

C ++ and Python sample code

Since C ++ calls Python and Python files (.py), you have to write code for each. Write C ++ on Visual Studio, create new text for Python, and write the test code below.

For C ++, define a python namespace and function

test_Cplus2_with_Python.cpp


#define BOOST_PYTHON_STATIC_LIB

#include <iostream>
#include <boost/python.hpp>

int main()
{
	//Namespace
	namespace py = boost::python;
	//Initialization
	Py_Initialize();
	//output
	std::cout << "Hello World! from C++ \n";

	//Python files(test_py.py)Import
	py::object module_ns = py::import("test_py").attr("__dict__");
	//Define functions in the imported file
	py::object get_and_return = module_ns["hello_from_python"];
	//Execute the imported function
	auto return_nd_array = get_and_return();
}

Make the Python file to be called a simple process as follows.

test_py.py


def hello_from_python():
        print("Hello World! from Python")

Folder structure

The C ++ code I just created test_Cplus2_with_Python → Write to test_Cplus2_with_Python.cpp, The Python code places x64 → Release → test_py.py.

Folder structure


test_Cplus2_with_Python(Self-made folder)
 ├── test_Cplus2_with_Python
 │  ├── test_Cplus2_with_Python.cpp 〇
 │  ├── test_Cplus2_with_Python.vcxproj
 │  ├── test_Cplus2_with_Python.vcxproj.filters
 │  ├── test_Cplus2_with_Python.vcxproj.user
 │  └── x64
 │  
 ├── x64 
 │  └── Release
 │       ├── test_Cplus2_with_Python.exe
 │       ├── test_Cplus2_with_Python.iobj
 │       ├── test_Cplus2_with_Python.ipdb
 │       ├── test_Cplus2_with_Python.pdb
 │       └── test_py.py 〇
 │ 
 └── test_Cplus2_with_Python.sln

Execution result

If you can output the C ++ and Python strings respectively, you are successful.

image.png

If you can't, -The settings on the project page are incorrect. -The code in the Python file is incorrect -The location of the Python file is incorrect -The boost installation is incorrect And so on.

Reflection

I don't think it's so common to call Python in C ++. It is useful when using Python's deep learning tools in C ++. I sincerely hope that it will be useful to various people, including juniors. If I can afford it, I would like to post an implementation of the object detection method (YOLOv3) using Python's deep learning in C ++.

Github Please for your reference.

URL


git clone https://github.com/yusa0827/200121_Cplus2_with_Python

Cloning and running doesn't work. Please reset your own environment path in visual studio.

Recommended Posts

Run Python in C ++ on Visual Studio 2017
Run Python YOLOv3 in C ++ on Visual Studio 2017
Python development in Visual Studio
Run AzureKinect in Python on Christmas Eve.
Bash, Python, Javascript, code command, etc. in Visual Studio Code on Mac
Next Python in C
Note on encoding when LANG = C in Python
Settings for Python coding in Visual Studio Code
TensorFlow: Run data learned in Python on Android
Extend python in C ++ (Boost.NumPy)
Run Openpose on Python (Windows)
Install numpy in Visual Studio 2019
Translator in Python from Visual Studio 2017 (Microsoft Translator Text API)
Run automatic jobs in python
Run shell commands in python
Run Python unittests in parallel
App development to tweet in Python from Visual Studio 2017
Try debugging Python on Raspberry Pi with Visual Studio.
Binary search in Python / C ++
Run Python CGI on CORESERVER
Bottle Pug in Visual studio 2019
Run unix command on python
Until you run server Django in Visual Studio Code
Japanese output when dealing with python in visual studio
AWS SDK for Python (Boto3) development in Visual Studio 2017
How to debug the Python standard library in Visual Studio
Do something like a Python interpreter in Visual Studio Code
Install python and Visual Studio Code on windows10 (April 2020 version)
Build Python3 for Windows 10 on ARM with Visual Studio 2019 (x86) on Windows 10 on ARM
Let's run "python -m antigravity" in python
Run shell command / python in R
ABC166 in Python A ~ C problem
Run Python on Schedule on AWS Lambda
Solve ABC036 A ~ C in Python
How to wrap C in Python
Remote debugging in Visual Studio (Linux)
Run Python scripts synchronously from C #
Solve ABC037 A ~ C in Python
Run a simple algorithm in Python
Write C unit tests in Python
Call C / C ++ from Python on Mac
Periodically run Python on Heroku Scheduler
How to install OpenCV on Cloud9 and run it in Python
A memo for those who use Python in Visual Studio (me)
Installation of Visual studio code and installation of python
Solve ABC175 A, B, C in Python
Run servo with Python on ESP32 (Windows)
Execute Python code on C ++ (using Boost.Python)
Find files like find on linux in Python
Notes on nfc.ContactlessFrontend () for nfcpy in python
Algorithm in Python (ABC 146 C Binary Search
Implement FIR filters in Python and C
[Python] Run Flask on Google App Engine
[C] [python] Read with AquesTalk on Linux
Write O_SYNC file in C and Python
Run the Python interpreter in a script
Run servomotor on Raspberry Pi 3 using python
[Python] Run Headless Chrome on AWS Lambda
Run Python code on A2019 Community Edition
Python Tools for Visual Studio Installation Guide
Generate C language from S-expressions in Python