Using standard io stream:stdin and stdout in a matlab exe

后端 未结 2 1758
星月不相逢
星月不相逢 2021-01-13 11:19

Question

I want it to \'listen\' to the standard input stream in a running (compiled) Matlab executable.

This is how I believe it is done in

相关标签:
2条回答
  • 2021-01-13 12:00

    Let me illustrate with a toy example. Consider the following MATLAB function:

    greet.m

    function greet()
        str = input('Enter your name: ','s');
        fprintf('Hello %s\n',str)
    end
    

    Now lets compile it into a standalone application. Note that if you use the deploytool tool, make sure to choose "Console application" NOT "Windows standalone application" as target. The latter apparently produces an executable where the standard input is connected to the system shell not the MATLAB command prompt..

    deploytool

    If you prefer to directly compile it yourself, use the following invocation:

    mcc -o hello -W main:hello -T link:exe -N -v greet.m
    

    (For reference, the "Windows app" target issues -W WinMain:hello instead)

    Running the executable produces:

    C:\> hello
    Enter your name: Amro
    Hello Amro
    

    where the input from the keyboard is correctly handled.

    0 讨论(0)
  • 2021-01-13 12:15

    It turns out that input reads the standard input stream.

    The reason why I failed to collect my inputs, is because I was using it as follows:

    input('prompt','s')
    

    As a result the string 'prompt' was sent to the program calling my application, and as it considered this an invalid response/request it did not send anything.

    I have succeeded in making a small test program, and unlike I suspected before it is NOT a problem that the other application doesn't hit enter after sending a command.

    The general solution

    This is the way I have my current setup,

    while 1
       stdin = input('','s'); % Note the empty first argument
       if ~isempty(stdin)
        stdout = process_input(stdin);
        stdout % Displaying the result (And thus sending it to stdout)
       end
    end
    
    0 讨论(0)
提交回复
热议问题