当前位置: 移动技术网 > IT编程>开发语言>C/C++ > C++调用Python脚本中的函数

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

2018年11月16日  | 移动技术网IT编程  | 我要评论

dj现场,我能歘 原唱,免费起名字大全

1.环境配置

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

然后在工程中包括进去

 

2.例子

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

这个脚本里面定义了两个函数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++代码可以引用它。

运行结果:

 

3.python代码处理

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

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

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

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

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

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网