飞道的博客

Python代码调用C/C++代码生成的exe可执行文件

336人阅读  评论(0)

一、C/C++主函数main中参数argc和argv含义及用法

我们常见的主函数如下所示:


  
  1. //C 语言中的主函数
  2. #include <stdio.h>
  3. int main(int argc, char* argv[])
  4. {
  5. return 0;
  6. }
  7. //C++ 中的主函数
  8. #include <iostream>
  9. using namespace std;
  10. int main(int argc, char* argv[])
  11. {
  12. return 0;
  13. }

主函数也是一个函数,也能够由外部的程序调用,其中argcargv就是主函数的两个参数。

1、argc 是 argument count 的缩写,表示传入main函数的参数个数

2、argv 是 argument vector 的缩写,表示传入main函数的参数序列或指针并且第一个参数argv[0]一定包含了程序所在完整路径的名称,所以确切的说需要我们输入的main函数的参数个数应该是argc-1个,示例如下:


  
  1. #include <iostream>
  2. using namespace std;
  3. void main(int argc, char* argv[])
  4. {
  5. //打印所有的参数
  6. for ( int i = 0; i < argc; i++)
  7. cout << "argument[" << i << "] is: " << argv[i] << endl;
  8. system( "pause");
  9. }

程序输出:

 

二、使用Python中的os.system()方法

使用os.system方法需要引入import os模块。(和C/C++中的System函数类似)

  1. 该函数用于将字符串转化为系统命令而执行。
  2. 该函数执行成功返回0,否则返回其他数字。返回的数字根据出错类型给出(1: Operation not permitted,2: No such file or directory …等)

示例:


  
  1. import os
  2. # 一些常用的网络命令
  3. os.system( "ping www.baidu.com")
  4. os.system( "ipconfig")

 

三、使用os.system调用exe文件

我们以C++程序为例,先编写一个加法函数,参数为a、b、c、d,返回a+b+c+d的值:


  
  1. #include <iostream>
  2. #include <string>
  3. using namespace std;
  4. //加法函数
  5. int addNumber(int a, int b, int c, int d)
  6. {
  7. return a + b + c + d;
  8. }
  9. //主函数
  10. void main(int argc, char* argv[])
  11. {
  12. int elem[ 4] = { 0 }; //参数数组
  13. //将参数转换为整数
  14. //第0个参数为路径+文件名,所以i从1开始
  15. for ( int i = 1; i < argc; i++)
  16. //stoi为string中的函数,即string to int,将字符串转换为整数
  17. elem[i - 1] = stoi(argv[i]); //将字符串转换为整数
  18. cout<< "addNumber函数的输出为:"<<addNumber(elem[ 0], elem[ 1], elem[ 2], elem[ 3]);
  19. system( "pause");
  20. }

将上述的C++代码编译执行,可能会报错,因为argv没有传入参数,会报出数组越界的错误,如下:

但是不会影响生成exe文件,将生成的exe文件和新建的python文件放在同一目录下(不放在同一路径下时,需要写绝对路径+文件名),在Python文件中写入如下代码


  
  1. import os
  2. a = input( '请输入a:')
  3. b = input( '请输入b:')
  4. c = input( '请输入c:')
  5. d = input( '请输入d:')
  6. os.system( "addNumber.exe" + " "+a+ " "+b+ " "+c+ " "+d)

注意,参数之间一定要用空格隔开

最后的输出如下:

 


转载:https://blog.csdn.net/qq_40836442/article/details/116332180
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场