Code-C++ Invoke Python

发布时间 2023-04-09 10:54:30作者: Theseus‘Ship

Code-C++ Invoke Python

https://www.cnblogs.com/yongchao/p/17299892.html

  1. https://www.cnblogs.com/lidabo/p/17043302.html
  2. https://blog.csdn.net/zong596568821xp/article/details/115690713

在调试过程中遇到以下问题:
1.window环境中,由于只有python39.lib,所以需要使用Release版本运行
2.linux环境中,Ubuntu22.04系统自带的python缺少Python.h文件,需要安装Python-dev。参考文章:https://www.cnblogs.com/yongchao/p/17299892.html

Code Demo

main.cpp

// main.cpp

////c++调用流程
//c++ 调用 python ,本质上是在 c++ 中启动了一个 python 解释器,由解释器对 python 相关的代码进行执行,执行完毕后释放资源,达到调用目的

#include <Python.h>
int main(int argc, char *argv[]) {
  // 初始化python解释器.C/C++中调用Python之前必须先初始化解释器
  Py_Initialize();
  
  // 执行一个简单的执行python脚本命令
  PyRun_SimpleString("print('hello world')\n");
 
  // 撤销Py_Initialize()和随后使用Python/C API函数进行的所有初始化
  Py_Finalize();
  return 0;
}

//---------------------------------------------------------------

//调用 python 模块以及模块中的函数,并且有可能需要参数传递以及返回值获取

//--------------------------------
//无参数传递的函数调用功能
//./script/inittest.py  init
#include <Python.h>
#include <iostream>
 
using namespace std;
 
int main(){
    // 初始化python接口  
	Py_Initialize();
	if(!Py_IsInitialized()){
		cout << "python init fail" << endl;
		return 0;
	}
    // 初始化python系统文件路径,保证可以访问到 .py文件,python文件在当前目录的script文件夹中,当前调用python文件为inittest.py,当前调用inittest.py中函数名为init
	PyRun_SimpleString("import sys");
	PyRun_SimpleString("sys.path.append('./script')");
 
    // 调用python文件名,不用写后缀
	PyObject* pModule = PyImport_ImportModule("inittest");
	if( pModule == NULL ){
		cout <<"module not found" << endl;
		return 1;
	}
    // 调用函数
	PyObject* pFunc = PyObject_GetAttrString(pModule, "init");
	if( !pFunc || !PyCallable_Check(pFunc)){
		cout <<"not found function add_num" << endl;
		return 0;
	}
    // 
    PyObject_CallObject(pFunc, NULL);
    // 结束python接口初始化
	Py_Finalize();
	return 0;
}

//--------------------------------

//有参函数调用
// test2.cpp
#include <Python.h> 
#include <iostream>
using namespace std;
 
int main()
{
    //初始化python接口
    Py_Initialize(); 
    
    //初始化使用的变量
    PyObject* pModule = NULL;
    PyObject* pFunc = NULL;
    PyObject* pName = NULL;
    
    //初始化python系统文件路径,保证可以访问到 .py文件
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./script')");
    
    //调用python文件名,只需要写文件的名称就可以了,不用写后缀。
    pModule = PyImport_ImportModule("inittest");
    
    //调用函数add
    pFunc = PyObject_GetAttrString(pModule, "add");
    
    //给python传参数
    // 函数调用的参数传递均是以元组的形式打包的,2表示参数个数
    PyObject* pArgs = PyTuple_New(2);
 
    // 0:第一个参数,传入 int 类型的值 1
    PyTuple_SetItem(pArgs, 0, Py_BuildValue("i", 1)); 
    // 1:第二个参数,传入 int 类型的值 2
    PyTuple_SetItem(pArgs, 1, Py_BuildValue("i", 2)); 
    
    //使用C++的python接口调用该函数
    PyObject* pReturn = PyEval_CallObject(pFunc, pArgs);
    
    //接收python计算好的返回值
    int nResult;
    // i表示转换成int型变量。
    // 在这里,最需要注意的是:PyArg_Parse的最后一个参数,必须加上“&”符号
    PyArg_Parse(pReturn, "i", &nResult);
    cout << "return result is " << nResult << endl;
    
    //结束python接口初始化
    Py_Finalize();

    return 0;
}

./script/inittest.py

def init():
    print("init test.")

def add(a,b):
    print("Now is in python module inittest/function add.")
    print("{} + {} = {}".format(a, b, a+b))
    return a + b

Others(待更新)

https://www.cnblogs.com/lidabo/p/17043302.html
参数类型、结构体等相关操作。