2011年12月19日 星期一

calling GNUPLOT from a c++ program

calling GNUPLOT from a c++ program
  • 底下透過popen() 進行,但在windows系統下,僅console application能夠用,欲在windows application 下執行,不能用popen() ,詳細請看最後面的Note說明
  • 欲在windows application 下執行,最簡單的方法還是將gnuplot 指令輸出成一個檔案,再用system () 呼叫



class GNUplot {
public:
GNUplot() throw(string);
~GNUplot();
void operator ()(const string& command);
// send any command to gnuplot
protected:
FILE *gnuplotpipe;
};

GNUplot::GNUplot() throw(string) {
gnuplotpipe=popen("gnuplot","w");
if (!gnuplotpipe) {
throw("Gnuplot not found !");
}
}

GNUplot::~GNUplot() {
fprintf(gnuplotpipe,"exit\n");
pclose(gnuplotpipe);
}

void GNUplot:operator() (const string& command) {
fprintf(gnuplotpipe,"%s\n",command.c_str());
fflush(gnuplotpipe);
// flush is necessary, nothing gets plotted else
};


You simply construct one object and invoke it with operator () like

GNUplot plotter;
plotter("plot sin(x)");

Note that GNUplot will be killed as soon as your program terminates. So
you need to wait for keystroke or similar, otherwise you will only see
short flashing of the graph. If you need that the graph window stays on
screen after your pragram fnished, then instead of "gnuplot" in the
constructor invoke "gnuplot -persist".


Ref.
http://www.velocityreviews.com/forums/t278698-calling-gnuplot-from-a-c-program.html
http://nxforce.blogspot.com/2008/07/cc-calling-gnuplot-in-c.html


Note Note
If used in a Windows program, the _popen function returns an invalid file pointer that causes the program to stop responding indefinitely. _popen works properly in a console application. To create a Windows application that redirects input and output, see Creating a Child Process with Redirected Input and Output in the Windows SDK.

  • _popen()
http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k%28POPEN%29;k%28DevLang-%22C%2B%2B%22%29;k%28TargetOS-WINDOWS%29&rd=true

  • C++ interface to Gnuplot via POSIX pipes
http://code.google.com/p/gnuplot-cpp/
此方法還是一樣用_popen(), windows program 可能不適用

  • 欲在 windows application中呼叫gnuplot 請參考底下這篇
http://code10111.blogspot.com/2011/06/call-gnuplot-from-c-program-in-windows.html
他的做法跟  Creating a Child Process with Redirected Input and Output 有些雷同




沒有留言:

張貼留言