C + + calls functions in Python scripts

Keywords: C++ Python

1. Environment configuration

After installing python, copy the include and lib of Python to your own project directory

And then include it in the project

 

2. examples

Write a python test script first, as follows

In this script, two functions are defined: Hello() and_add(). The file name of my script is mytest.py

C++ Code:

#include "stdafx.h"  
#include <stdlib.h>
#include <iostream>  

#include "include\Python.h"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    //Initialization Python Environmental Science  
    Py_Initialize();

    PyRun_SimpleString("import sys");
    //Add to Insert Module path  
    //PyRun_SimpleString(chdir_cmd.c_str());
    PyRun_SimpleString("sys.path.append('./')");

    //Import module  
    PyObject* pModule = PyImport_ImportModule("mytest");

    if (!pModule)
    {
        cout << "Python get module failed." << endl;
        return 0;
    }

    cout << "Python get module succeed." << endl;

    PyObject * pFunc = NULL;
    pFunc = PyObject_GetAttrString(pModule, "Hello");
    PyEval_CallObject(pFunc, NULL);

    //Obtain Insert In module_add function  
    PyObject* pv = PyObject_GetAttrString(pModule, "_add");
    if (!pv || !PyCallable_Check(pv))
    {
        cout << "Can't find funftion (_add)" << endl;
        return 0;
    }
    cout << "Get function (_add) succeed." << endl;

    //Initialize the parameters to be passed in, args Mode configured to pass in two parameters  
    PyObject* args = PyTuple_New(2);
    //take Long Data conversion to Python Acceptable types  
    PyObject* arg1 = PyLong_FromLong(4);
    PyObject* arg2 = PyLong_FromLong(3);

    //take arg1 Configured as arg First parameter brought in  
    PyTuple_SetItem(args, 0, arg1);
    //take arg1 Configured as arg The second parameter brought in  
    PyTuple_SetItem(args, 1, arg2);

    //Call the function with the passed in parameter and get the return value  
    PyObject* pRet = PyObject_CallObject(pv, args);

    if (pRet)
    {
        //Convert return value to long type  
        long result = PyLong_AsLong(pRet);
        cout << "result:" << result << endl ;
    }

    Py_Finalize();

    system("pause");

    return 0;
}

Note where the script is placed to ensure that C + + code can reference it.

Operation result:

 

3.python code processing

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

To run the exe in the above Debug directory independently, you must copy the python script. In order not to let others directly see my code, I copied the generated. pyc file

After copying, modify the file name to:

A simple encryption of python code is implemented.

It's said that it can be decompiled, but it's enough for me.

Posted by jini01 on Fri, 06 Dec 2019 12:43:08 -0800