【python代码执行过程中调用cpp代码】

cpp代码

#include <iostream>
using namespace std;

int add(int argc, char** argv)
{   
    
    if (argc < 4) {
        cout << "please input parameters:"
            << "for example:\nadd 2 3\nyou will get a return 5"
            << endl;
                   
        return 0;
    }
    std::string func = argv[1];
    double num1 = atof(((std::string)argv[2]).c_str());
    double num2 = atof(((std::string)argv[3]).c_str());

    if (func == "add") {
        cout << num1 << " + " << num2 << " = " << num1 + num2 << endl;
    }
    if (func == "sub") {
        cout << num1 << " - " << num2 << " = " << num1 - num2 << endl;
    }
    return 0;
}

【语言间调用】python调用C++的exe并输入参数

python代码

import os
import subprocess
print("苹果")
result = subprocess.run(['./Project1.exe','add','2','3'])

python运行结果

在这里插入图片描述
很可惜,我的需求:传给cpp代码的参数特别大,无法通过参数来传递o(TヘTo)
我想的还是通过读写文件来传递

所以,先写成篇博客,记录一下以备不时之需

猜你喜欢

转载自blog.csdn.net/Peanut31434331/article/details/133552064
今日推荐