且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

运行m文件后如何关闭GNU Octave,而又不关闭绘图窗口?

更新时间:2023-02-20 15:00:18

您可以使用八度API从程序内部调用脚本.在那里,创建一个子进程,该进程调用八度,因此父进程可以结束.这样,您可以保持八度运行.使用此方法,就没有八度音阶CLI,因为您通过API(特别是feval)进行了所有八度音阶调用.

You can use the octave API to call the script from within your program. There, create a child process, which calls octave, so the parent process can end. With this, you can keep octave running. With this method, there is no octave CLI, since you do all calls to octave via the API, especially feval.

不幸的是,使用API​​的指南非常糟糕,但是我为您整理了一些应该可行的方法.它基本上只读取脚本并执行相应的功能.关于此方法,这很不错:您可以使用普通的倍频程函数/脚本文件方法编写所有内容.

Unfortunately, the guide on using the API is very bad, but i put something together for you which should work. It basically only reads a script and executes the corresponding function. This is the nice thing about this method: you can write everything using normal octave function/script file methods.

我在八度文件中添加了printf语句,以显示如何将参数传递至八度.

I added the printf statement in the octave file in order to show how you can pass arguments to octave.

#include <iostream>

#include <unistd.h>

#include <octave/oct.h>
#include <octave/octave.h>
#include <octave/parse.h>
#include <octave/toplev.h>

int main()
{
    pid_t pid = fork();

    if(pid != 0) // parent
    {
        std::cout << "parent, exiting\n";
    }
    else
    {
        // arguments for octave
        string_vector argv (2);
        argv(0) = "embedded";
        argv(1) = "-q"; // quiet

        // start octave, run embedded (third parameter == true)
        octave_main (2, argv.c_str_vec (), true);

        // read the script file
        source_file("calc_and_plot.m");

        // call the function with an argument
        octave_value_list in;
        in(0) = "Hello, world.";
        feval("calc_and_plot", in);


        std::cout << "octave (child process) done\n";
        clean_up_and_exit(0); // quit octave. This also quits the program,
                              // so use this together with atexit, if you 
                              // need to do something else after octave exits
    }

    return 0;
}

八度脚本/功能文件

function calc_and_plot(str)
    printf('%s\n', str);
    x = linspace(0, 2*pi, 100);
    y = sin(x);
    it = plot(y);
    waitfor(it);
end

使用以下命令编译main.cpp:

Compile the main.cpp with

g++ main.cpp -L/usr/lib/octave-4.0.2 -I/usr/include/octave-4.0.2 -loctave -loctinterp

您必须调整系统和八度音阶版本的路径.您也可以使用mkoctfile命令,该命令基本上是相同的.您可以查看其-p开关的输出,例如

You have to adjust the paths to your system and octave version. You can also use the mkoctfile command, which basically does the same. You can look at the output of its -p switch, e.g.

mkoctfile -p CFLAGS

获取库,编译器标志等.有关此内容,请参见手册页.

to get the libs, compiler flags etc. Have a look at the manpage for this.