lava / matplotlib-cpp

Extremely simple yet powerful header-only C++ plotting library built on the popular matplotlib
MIT License
4.28k stars 1.12k forks source link

Segmentation Fault when matplotlib for python 3 uses Qt5Agg backend #268

Open pascal-mueller opened 3 years ago

pascal-mueller commented 3 years ago

When compiling against python 3 with numpy 3 and if matplotlib uses Qt5Agg as it's backend, we receive a seg. fault.

Example:

#include "matplotlibcpp.h"

namespace plt = matplotlibcpp;

int main() {
    plt::plot({1,3,2,4});
    plt::show();
}

compiled with for example g++ minimal.cpp -std=c++11 -I/usr/include/python3.9 -I/usr/lib/python3.9/site-packages/numpy/core/include/ -lpython3.9

in my case it turned out that matplotlib uses Qt5Agg which results in the seg fault. We can set the backend explicitly and then it works:

#include "matplotlibcpp.h"

namespace plt = matplotlibcpp;

int main() {
    plt::backend("TkAgg");
    plt::plot({1,3,2,4});
    plt::show();
}

See also: https://stackoverflow.com/questions/67533541/py-finalize-resulting-in-segmentation-fault-for-python-3-9-but-not-for-python/67577360#67577360

amadeus84 commented 2 years ago

Following up on unddoch's analysis on stackoverflow https://stackoverflow.com/questions/67533541/py-finalize-resulting-in-segmentation-fault-for-python-3-9-but-not-for-python/67577360#67577360 .

In basic.cpp, adding

plt::detail::_interpreter::kill();

just before return from main, fixes the segfault. Compiled the code like this:

g++ -g -Wall -o basic -I/usr/include/python3.9 basic.cpp -lpython3.9

No other changes (like setting the backend to TkAgg) were necessary.