Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use C++ to call Python code

Shulou Source: shulou.com Published: 2022-06-03 11:12:45 10月11日 Update

This article mainly introduces how to use C++ to call Python code, the article is very detailed, has a certain reference value, interested friends must read!

I. configuring the python environment

1. First install Python (version doesn't matter), and add the python path to the environment variable when installing.

The folder after installation is as follows:

two。 Right-click Project-> Properties-> VC++ directory in VS to configure the environment and libraries

1) include directories:

Python installation path / include

2) Library directory:

Python installation path / libs

Right-click item-> Properties-> Connector-> input-> attach dependent Library

Under debug:

Python installation directory / libs/python37_d.lib

Under release:

Python installation directory / libs/python37.lib

Be careful

1. Debug may not be configured with python37_d.lib, so just copy a python37.lib and rename it to python37_d.lib.

2. If you keep reporting errors, but there is no problem including header files, then you need to see whether your python is 32-bit or 64-bit. Then configure the vs environment according to the python environment.

C++ calls the python function and outputs the return value

First of all, there may be a hole! Be sure to make sure that the file where the python function is located is working properly! Then put the python code in the same directory as the C++ code.

1. Define Python function

#! python3#-*-coding:utf-8-*-import base64import hmacfrom hashlib import sha1def hash_hmac (code, key): # sha1 encryption signature algorithm hmac_code = hmac.new (key.encode (), code.encode (), sha1). Digest () return base64.b64encode (hmac_code). Decode ()

2. Write C++ code

# include # includeusing 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 ("hash_hmac"); / / here is the file name hash_hmac.py if (pModule = = NULL) {cout

Tags: File code function object type caching action character string time directory parameter format environment build run program path configuration two Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology NVidia MariaDB vpn Shulou Information