Detailed explanation of the method of calling Python code with C + +


1、 Configuring Python environment issues

1. First install python (the version doesn’t matter). When installing, add the python path to the environment variable

The folder after installation is as follows:


2. Configure environment and Library in vs. right click Project – > properties – > VC + + directory

1) Include directory:

Python installation path / include

2) Library Directory:

Python installation path / LIBS

Right click the item – > properties – > connector – > Input – > attach dependency library

Under debug:

Python installation directory / LIBS / python37_ d.lib

Under release:

Python installation directory / LIBS / python37.0 lib

be careful

1. Python 37 may not be available during debug configuration_ d. Lib, then put Python 37 Lib copy one and rename it Python 37_ d. Lib is OK

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

2、 C + + calls Python functions and outputs the return value

First, there may be a pit! Make sure that the file where the python function is located can run normally! Then put the Python code in the same directory as the C + + code.

1. Define Python functions

# -*- coding:utf-8 -*-
import base64
import hmac
from hashlib import sha1

def hash_hmac(code , key):
 #SHA1 encryption signature algorithm
 hmac_code = , code.encode() , sha1).digest()
 return base64.b64encode(hmac_code).decode()

2. Writing C + + code

#include <iostream>
using namespace std;
int main()
 Py_ Initialize();// Before using python, call py_ Initialize(); 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;// Declare variable
 PyObject* pFunc = NULL;//  Declare variable
 pModule = PyImport_ ImportModule("hash_hmac");// Here is the file name hash to call_ hmac. py
 if (pModule == NULL)
 Cout < < not found < < endl;
 pFunc = PyObject_ GetAttrString(pModule, "hash_hmac");// Here is the name of the function to be called
 //Two string parameters
 PyObject* pParams = Py_BuildValue("(ss)", "/oss/upload?bucket=test&filekey=test/image/3b/3ba9d94cab2f8868823d71c4445e125a.png\n" , "q4mJAS777BUbbdVpEqh2XRcZZqNyDweU4GRnM690");
 char* result;
 PyObject* pRet = PyObject_ CallObject(pFunc, pParams);// Call function
 int res = 0;
 PyArg_ Parse(pRet, "s", &result);// Conversion return type
 cout << "res:" << result << endl;// Output results
 Py_ Finalize();// Call PY_ Finalize, this root PY_ Corresponding to initialize.
 return 0;

3. Explain some C + + code

PyObject* pParams = Py_BuildValue("(ss)", "/oss/upload?bucket=test&filekey=test/image/3b/3ba9d94cab2f8868823d71c4445e125a.png\n" , "q4mJAS777BUbbdVpEqh2XRcZZqNyDweU4GRnM690");

Here I enter two string type parameters, py_ The role of buildvalue() function and pyarg_ Parsetuple () does the opposite by converting a C-type data structure into a python object.

This function can be used with pyarg_ The parsetuple () function recognizes a series of format strings, but the input parameters can only be values, not pointers.

It returns a python object and pyarg_ The difference between parsetuple() and pyarg()_ Parsetuple() function. Its first parameter is tuple, py_ Buildvalue() does not necessarily generate a tuple. It generates a tuple only when the format string contains two or more format units. If the format string is empty, it returns none.

In the following description, the item in brackets is the python object type returned by the format unit, and the item in square brackets is the type of C value passed.

“S” (string) [char *]: converts a C string into a python object. If the C string is empty, it returns none.

“S#” (string) [char *, int]: converts the C string and its length into a python object. If the C string is a null pointer, the length is ignored and none is returned.

“Z” (string or none) [char *]: same as “s”.

“Z#” (string or none) [char *, int]: same as “s#”.

“I” (integer) [int]: converts an int of type C to a python int object.

“B” (integer) [char]: same as “I”.

“H” (integer) [short int]: same as “I”.

“L” (integer) [long int]: converts a long of type C to an int object in pyhon.

“C” (string of length 1) [char]: converts a char of type C to a Python string object of length 1.

“D” (float) [double]: converts a double of type C into a floating-point object in Python.

“F” (float) [float]: same as “d”.

“O &” (object) [converter, anything]: convert any data type into a python object through a conversion function. These data are called as parameters of the conversion function and a new Python object is returned. If an error occurs, null is returned.

“(items)” (tuple) [matching items]: converts a series of C values into Python tuples.

“[items] (list) [matching items]: converts a series of C values into a python list.

“{items}” (Dictionary) [matching items]: convert the C value of a series of classes into a python dictionary, and each pair of continuous C values will be converted into a key value pair.

For example:

Py_BuildValue(“”) None

Py_BuildValue(“i”, 123) 123

Py_BuildValue(“iii”, 123, 456, 789) (123, 456, 789)

Py_BuildValue(“s”, “hello”) ‘hello’

Py_BuildValue(“ss”, “hello”, “world”) (‘hello’, ‘world’)

Py_BuildValue(“s#”, “hello”, 4) ‘hell’

Py_BuildValue(“()”) ()

Py_BuildValue(“(i)”, 123) (123,)

Py_BuildValue(“(ii)”, 123, 456) (123, 456)

Py_BuildValue(“(i,i)”, 123, 456) (123, 456)

Py_BuildValue(“[i,i]”, 123, 456) [123, 456] Py_BuildValue(“{s:i,s:i}”, “abc”, 123, “def”, 456) {‘abc’: 123, ‘def’: 456}

Py_BuildValue(“((ii)(ii)) (ii)”, 1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6))

3. Running C + + programs

Same as expected by Python code.


3、 Python code processing

When releasing software, we usually don’t want the code to be seen directly by others.

If the EXE in the above debug directory wants to run independently, you must copy the python script. In order not to let others see my code directly, what I copied was generated PyC file to achieve a simple encryption of Python code. But it is said that it can be decompiled, but it’s enough for me.

4、 A Py and The difference between PyC

In the original Python program, the original program code is placed in Py file, and python will execute Py file. Will Py form of the program compiled into an intermediate file (byte – compiled) PyC file. The purpose of this is to speed up the execution of the file next time.

Therefore, when we run the python file, we will automatically check whether it has PyC files, if any, and Py file modification time and PyC will be read when the modification time is the same PyC file, otherwise Python will read the original Py file.

In fact, not all Py files will be generated during and running PyC file, only in the corresponding import Py file, the corresponding will be generated PyC file.

5、 Use Py generation pyc

Use the following commands on the command line:

python -m py_ compile test. Py# single file
python -m py_ compile /root/src/{file1,file2}. Py# multiple files


The above is a detailed explanation of the method of using C + + to call Python code introduced by Xiaobian. I hope it will be helpful to you!

Recommended Today

Chapter 45 SQL command from (I)

Chapter 45 SQL command from (I) A select clause that specifies one or more tables to query. outline SELECT … FROM [optimize-option] table-ref [[AS] t-alias][,table-ref [[AS] t-alias]][,…] parameter optimize-optioN – optional – specifies a single keyword or a series of keywords separated by spaces for query optimization options (optimizer tips). The following keywords are supported:%ALLINDEX、%FIRSTTABLE […]