c/c++语言开发共享C++调用Python脚本中的函数

1.环境配置 安装完python后,把python的include和lib拷贝到自己的工程目录下 然后在工程中包括进去 2.例子 先写一个python的测试脚本,如下 这个脚本里面定义了两个函数Hello()和_add()。我的脚本的文件名叫mytest.py C++代码: 注意脚本放的位置,确保C …


1.环境配置

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

然后在工程中包括进去

 

2.例子

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

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

c++代码:

#include "stdafx.h"    #include <stdlib.h>  #include <iostream>      #include "includepython.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代码的加密。

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

 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/606275.html

(0)
上一篇 2021年5月13日
下一篇 2021年5月13日

精彩推荐