Cpp调用Python3,使用matplotlib画(二维)图----2. CPP编写

Posted groundhogpaul

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Cpp调用Python3,使用matplotlib画(二维)图----2. CPP编写相关的知识,希望对你有一定的参考价值。

---恢复内容开始---

直接上代码吧

# include <iostream>
# include <Python.h>


int main()

Py_SetPythonHome(L"D:\\ProgramFiles\\Python37");
Py_Initialize();  // 按照上一篇博客,到这一步应该是成功的
PyRun_SimpleString("import matplotlib.pyplot as plt"); /*调用python文件*/

//以下两步,是因为matplotlib为了帮你服务方便,会读取你在哪个文件搞事情,
  //然而我们是用CPP调用的,没有文件,它就崩了。
  //报错:index error: out of list (sys.argv)
  //所以就给它赋值一个引子文件,(这个文件都不需要真实存在),
  //具体我还不明白,我是在debug的过程中蒙的。

  PyRun_SimpleString("import sys");  
PyRun_SimpleString("sys.argv = [‘test.py‘]");  

PyRun_SimpleString("plt.plot([1,2,3,4], [12,3,23,231])"); /*调用python文件*/
PyRun_SimpleString("plt.plot()");

PyRun_SimpleString("plt.show()"); /*调用python文件*/
Py_Finalize();
return 0;

 

以上是关于Cpp调用Python3,使用matplotlib画(二维)图----2. CPP编写的主要内容,如果未能解决你的问题,请参考以下文章