user1007692
user1007692

Reputation: 307

Matlab system function with a C executable

I have written a Matlab GUI for my C program. I thought about using MEX, but there are too many C files and C program requires a DLL to run.

So, instead I have the Matlab System function calling the executable with inputs, something like [status results] = system('executable "input 1" "input 2"'), which runs well, but I want real time output. results is just a percent output of how complete the program is, and I want to use this output for a GUI progress bar in Matlab.

The output does get stored into results, but only after the program is complete. Thus, making the progress bar pointless.

Is it possible to get the executable to send outputs one at a time to Matlab, and then have Matlab update the progress bar, and return to the executable?

Edit: I'm looking for a solution in Windows.

Upvotes: 0

Views: 1344

Answers (2)

user1007692
user1007692

Reputation: 307

I found a solution. Credit goes to Richard Alcock at Matlab Central

Specifically, for my solution:

cmd = {'executable.exe', 'input 1', 'input 2'};
processBuilder = java.lang.ProcessBuilder(cmd);
cmdProcess = processBuilder.start();

% Set up a reader to read the output from the command prompt
reader = 
    java.io.BufferedReader(...
        java.io.InputStreamReader(...
            cmdProcess.getInputStream() ...
        ) ...
    );

% Loop until there is some output
nextLine = char( reader.readLine );
while isempty(nextLine) 
    nextLine = char( reader.readLine );
end

% Then loop until there is no more output
while ~isempty(nextLine);
    fprintf('Output: %s\n', nextLine);
    nextLine = char( reader.readLine );
end

% Get the exit value of the process
exitValue = cmdProcess.exitValue  

Note: this code does not hold up the executable. The executable must finish before this code finishes, otherwise this code crashes when it gets ahead of the executable.

Upvotes: 1

John
John

Reputation: 5905

I only see two options, and neither fits directly with your current implementation approach.

The first, is to just use sockets to communicate between the two. Here's a pure matlab socket implementation, but under the hood it's using C sockets. It's been 10 years since I've done C/Java socket comms, but I recall that at the time there were some issues.

http://www.mathworks.com/matlabcentral/fileexchange/21131-tcpip-socket-communications-in-matlab

Another option is to have your executable be accessible via a C DLL from matlab, and call the DLL directly from matlab (i.e. have matlab control your app). This is the way I've been doing most such interactions lately, and it works very well.

http://www.mathworks.com/help/techdoc/ref/loadlibrary.html

Upvotes: 2

Related Questions