VS Code下配置C++调用python程序

网上VS Code配置C++调用python的方法很少,我来贡献一份

1.配置VSCodeC++环境(建议重新配置一下防止有啥魔幻错误)
说是配置其实是傻瓜安装
链接:https://pan.baidu.com/s/1wl796juGpfW2xjljEx4mAQ
提取码:b53p
跟着配置就好没啥好说的。

2. 环境配置
按下ctrl + shift + p 输入 c/c++

在这里插入图片描述
此处填写python的include路径
在这里插入图片描述
ctrl + shit + b 运行之前先配置一下 task
在这里插入图片描述
填写链接器
在这里插入图片描述

** 3. 测试文件**
创建一个C++文件

#define  _hypot hypot        //有的可能会报错没有这个文件,你可以先去掉看一眼,没有报错就可以不用写了
#include "D:\\Anaconda\\include\\Python.h"  //这要用绝对路径,我也不知道咋解决要是有朋友知道评论留言一下,谢谢了。
#include <iostream>

using namespace std;

int main()
{

	Py_SetPythonHome(L"D:\\Anaconda");
	/**
	这句语句是在添加python.exe所在路径,不添加虽然编译没有问题,但是会在运行时出现
	Fatal Python error: initfsencoding: unable to load the file system codec
	ModuleNotFoundError: No module named 'encodings'
	这种很无厘头的错误
	**/
	Py_Initialize();//使用python之前,要调用Py_Initialize();这个函数进行初始化
	if (!Py_IsInitialized())
	{
		printf("初始化失败!");
		return 0;
	}
	else {
		PyRun_SimpleString("import sys");
		PyRun_SimpleString("sys.path.append('./')");//这一步很重要,修改Python路径


		PyObject * pModule = NULL;//声明变量
		PyObject * pFunc = NULL;// 声明变量

		pModule = PyImport_ImportModule("hello");//这里是要调用的文件名hello.py
		if (pModule == NULL)
		{
			cout << "没找到该Python文件" << endl;
		}
		else {
			pFunc = PyObject_GetAttrString(pModule, "add");//这里是要调用的函数名
			PyObject* args = Py_BuildValue("(ii)", 28, 103);//给python函数参数赋值

			PyObject* pRet = PyObject_CallObject(pFunc, args);//调用函数

			int res = 0;
			PyArg_Parse(pRet, "i", &res);//转换返回类型

			cout << "res:" << res << endl;//输出结果
		}
		Py_Finalize();//调用Py_Finalize,这个根Py_Initialize相对应的。
	}
	return 0;
}

创建hello.py文件

def add(a,b):  
    print ("These consequences are from Python code.")  
    print ("a = " + str(a))  
    print ("b = " + str(b))  
    print ("ret = " + str(a+b))  
    return a + b

运行结果为说明配置成功了
在这里插入图片描述

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用Python的eval()函数来计算表达式,包括字符串。可以通过在C++调用Python的解释器来使用该函数。同时,你可以使用Python的字符串格式化功能,将C++字符串传递给Python程序使用。 以下是一个示例代码: C++ 代码: ```c++ #include <Python.h> int main() { // Initialize Python interpreter Py_Initialize(); // Execute Python code PyRun_SimpleString("import math\n"); PyRun_SimpleString("result = eval('5 + 2 * 3 + math.sqrt(16)')\n"); // Get the result PyObject* pResult = PyDict_GetItemString(PyEval_GetGlobals(), "result"); double result = PyFloat_AsDouble(pResult); // Print the result printf("Result: %f\n", result); // Cleanup Py_DECREF(pResult); Py_Finalize(); return 0; } ``` 该代码使用Python的eval()函数计算了表达式"5 + 2 * 3 + math.sqrt(16)",其中math.sqrt()函数计算了16的平方根。结果存储在名为"result"的Python变量中,并从C++代码中检索和打印。注意,在上面的代码中,我们使用了PyDict_GetItemString()和PyFloat_AsDouble()函数来检索Python变量的值。 如果你想在表达式中包含字符串,可以使用字符串格式化功能。例如: ```c++ #include <Python.h> int main() { // Initialize Python interpreter Py_Initialize(); // Prepare the Python code with a string placeholder const char* code = "value = eval('%s')\n"; // Format the code with the expression and register the string const char* expression = "1 + 2 + 3 + len('hello')"; PyObject* pCode = PyUnicode_FromFormat(code, expression); // Execute the Python code PyRun_SimpleString("string = 'hello from C++'\n"); PyRun_SimpleString(PyUnicode_AsUTF8(pCode)); // Get the result PyObject* pResult = PyDict_GetItemString(PyEval_GetGlobals(), "value"); int result = PyLong_AsLong(pResult); // Print the result printf("Result: %d\n", result); // Cleanup Py_DECREF(pResult); Py_DECREF(pCode); Py_Finalize(); return 0; } ``` 在上面的代码中,我们使用了PyUnicode_FromFormat()函数来格式化Python代码,将表达式作为字符串参数传递到eval()函数中。我们还在Python代码中注册了一个名为"string"的变量。注意,在C++代码中,我们使用了PyUnicode_AsUTF8()函数将格式化的Python代码转换为UTF-8字符串。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值