C++调用Python脚本中的函数

1.环境配置

安装完python后,把python的include和lib拷贝到自己的工程目录下

image

然后在工程中包括进去

imageimage

 

2.例子

先写一个python的测试脚本,如下

image

这个脚本里面定义了两个函数Hello()和_add()。我的脚本的文件名叫mytest.py

C++代码:

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

#include "include\Python.h"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    //初始化Python环境  
    Py_Initialize();

    PyRun_SimpleString("import sys");
    //添加Insert模块路径  
    //PyRun_SimpleString(chdir_cmd.c_str());
    PyRun_SimpleString("sys.path.append('./')");

    //导入模块  
    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);

    //获取Insert模块内_add函数  
    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;

    //初始化要传入的参数,args配置成传入两个参数的模式  
    PyObject* args = PyTuple_New(2);
    //将Long型数据转换成Python可接收的类型  
    PyObject* arg1 = PyLong_FromLong(4);
    PyObject* arg2 = PyLong_FromLong(3);

    //将arg1配置为arg带入的第一个参数  
    PyTuple_SetItem(args, 0, arg1);
    //将arg1配置为arg带入的第二个参数  
    PyTuple_SetItem(args, 1, arg2);

    //传入参数调用函数,并获取返回值  
    PyObject* pRet = PyObject_CallObject(pv, args);

    if (pRet)
    {
        //将返回值转换成long型  
        long result = PyLong_AsLong(pRet);
        cout << "result:" << result << endl ;
    }

    Py_Finalize();

    system("pause");

    return 0;
}

注意脚本放的位置,确保C++代码可以引用它。

运行结果:

image

 

3.python代码处理

在发布软件的时候,通常我们都不希望代码可以直接被别人看到。

以上的Debug目录中的exe要想能够单独运行,必须把python脚本拷过去。为了不让别人能直接看到我的代码,我拷过去的是生成的.pyc文件

image

拷过去之后修改文件名为:

image

实现了一个简单的python代码的加密。

不过据说可以反编译,但是对我来说已经够了。

 

posted @ 2018-11-15 21:49  yeren2046  阅读(31852)  评论(0编辑  收藏  举报