Calling Python from C++

Click the above“Mechanical and Electronic Engineering Technology” to follow us

1. Configure Header Files

Add the include directory under the Python installation directory to the header file directory. The operation path in Visual Studio 2022 is: Properties –> C/C++ -> General-> Additional Include Directories

Calling Python from C++

C:\Users\AppData\Local\Programs\Python\Python39\include

2. Configure lib Directory

Add Python39.lib to the compilation link. The operation path in Visual Studio is: Properties –> Linker -> General -> Additional Library Directories

Calling Python from C++

C:\Users\AppData\Local\Programs\Python\Python39\libs

3. Add Additional Dependencies

Copy python39.lib from the libs directory in the project and rename it to python39_d.lib. Fill in the content of the additional dependencies as C:\Users\AppData\Local\Programs\Python\Python39\libs\python39_d.lib; as shown in the figure:

Calling Python from C++

4. Test

Execute the following code:

#include <iostream>
#include "python.h"
int main(){  Py_Initialize();  PyRun_SimpleStringFlags("print('hello world') ", NULL);  Py_Finalize();}

Calling Python from C++

Calling Python from C++

Want to learn more

Quickly scan the code to follow

Leave a Comment