Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to call python code in C++

2025-02-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces how to call python code in C++, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to know about it.

I. Environmental settings

Windows

VS2015

Python uses the python environment that comes with acaconda. Different versions of acaconda come with different python. Mine is python3.6 (this step is very important. If you use the python of the virtual environment created by acaconda, it may not be successful.)

2. Set up in the VS project (1) first find the include folder and libs folder in acaconda, as shown in the figure

Then right-click the C++ project, select Properties, click the VC++ directory, then add the include folder in the include directory, and add the libs folder in the library directory

(2) Click the linker, then enter, attach dependencies, and add the path of python36_d.lib

Because it is configured as Debug, python36_d.lib is added instead of python36.lib. If you don't have this file, just copy python36.lib and name it python36_d.lib. As shown in the figure

(3) python code

To call the max function of vsdemo.py in python in C++ code, first the python code looks like this

Def max (if b): if a > b: return an else: return b

The C++ code is shown in the figure.

# include#include # include "stdio.h" using namespace std;int main () {Py_Initialize (); / / call Py_Initialize () before using python; this function initializes if (! Py_IsInitialized ()) {printf ("initialization failed!") ; return 0;} PyRun_SimpleString ("import sys"); PyRun_SimpleString ("sys.path.append ('. /')"); / / this step is very important. Modify the Python path PyObject* pModule = NULL;// declaration variable PyObject* pFunc = NULL;// declaration variable pModule = PyImport_ImportModule ("vsdemo") / / here is the file name vsdemo.py if (pModule = = NULL) {cout to be called

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report