1. 说明
在 C++ 项目中直接绘制结果向量的图像不是很方便,往往需要图形界面框架。github 项目 matplotlib-cpp 能够实现在 C++ 项目中调用 python 的 matplotlib 绘图库。
2. 过程
2.1 安装 python、numpy 和 matplotlib(注意安装debug模块,和版本对应)
2.2 安装 vcpkg 包管理器(注意关闭杀毒软件,避免生成不了exe文件)
在想要安装的路径下打开 window terminal,执行
git clone https://github.com/microsoft/vcpkg
cd vcpkg
.\bootstrap-vcpkg.bat
.\vcpkg integrate install
执行完毕后,vcpkg 就被集成到了 VS2019 中。
2.3 安装 matplotlib-cpp(注意对应版本,是64位还是32位。网路条件要好安装power7.2.5和7z)
.\vcpkg install matplotlib-cpp
.\vcpkg install matplotlib-cpp:x64-windows
3.配置vs codes
使用vs2019编译各种错误,最后放弃。转为使用Cmake+vscode编译成功了,下面是CMakeLists.txt文件
cmake_minimum_required(VERSION 3.7)
project (MatplotlibCPP_Test)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include_directories(C:/Users/N014600001792/AppData/Local/Programs/Python/Python310/include)
include_directories(C:/Users/N014600001792/AppData/Local/Programs/Python/Python310/Lib/site-packages/numpy/core/include)
link_directories(C:/Users/N014600001792/AppData/Local/Programs/Python/Python310/libs)
add_definitions(-DMATPLOTLIBCPP_PYTHON_HEADER=Python.h)
add_executable(minimal ${CMAKE_CURRENT_SOURCE_DIR}/examples/minimal.cpp)
target_link_libraries(minimal _tkinter.lib)
target_link_libraries(minimal python3.lib)
target_link_libraries(minimal python3_d.lib)
target_link_libraries(minimal python310.lib)
target_link_libraries(minimal python310_d.lib)
4. 配置 VS2019
3.1 添加附加包含目录
打开项目 --> 属性。
在 C++ --> 常规 中添加本地 python 的 include 文件夹路径和 numpy 的 include 路径。
3.2 添加附加库目录
在 链接器 --> 常规 中添加 python libs 路径。
3.3 input
在 链接器 --> 输入 中添加 python 的 lib 文件。
3.4 修改 matplotcpp.h 文件
打开 matplotlib-cpp.h 文件,在头文件中添加 `include <string>`。不然会报"命名空间 std 没有成员 stod"的错误。
关于这个错误,我查看项目的 github 仓库,源文件中已经添加了 string 头文件,但通过 vcpkg 安装的版本仍需添加。
注释掉 340 行左右的两个 template 定义。
4. 效果
使用时只需要添加头文件和命名空间,把想要查看的向量传入 plot 即可。
#include "../matplotlibcpp.h"
namespace plt = matplotlibcpp;
int main() {
plt::plot({1,3,2,4});
plt::show();
}