MATLAB: How to have System.Console.WriteLine write to the MATLAB command window while using the .NET API in MATLAB 7.8 (R2009a)

consoleMATLABnetsystemwriteline

I have a C# .NET assembly (MATLABWriter.dll) project with the following code:
namespace MATLABWriter {
public class WriterClass {
public void Write() {
System.Console.Write("Hello, world!");
}
}
}
I have loaded the .NET DLL in MATLAB using the NET.addAssembly command:
>> NET.addAssembly("MATLABWriter.dll");
>> writerObj = MATLABWriter. WriterClass;
The Write() method has a call to System.Console.Write to write the specific text out to the command window.
However, if I execute the Write() method, MATLAB does not print the text:
>> writerObj.Write
Is there a way to write this text to the MATLAB command window?

Best Answer

The ability to have System.Console.WriteLine write to the MATLAB command window is not available in MATLAB 7.8 (R2009a).
To work around this issue, use the following MATLAB code:
function output = captureConsole(myMethod)
%Capture the output of Console.Write or Console.WriteLine in MATLAB
% Input: A string to pass it to Console.Write method
% Output: Captured output
import System.*
%create a streamwriter class
writer = IO.StreamWriter(IO.MemoryStream);
%save the old console
oldConsole = Console.Out;
%set the new console output
Console.SetOut(writer);
%set the stream length to 0
stream = writer.BaseStream;
stream.SetLength(0);
% Call a method that prints out a string
evalin('base',myMethod)
%capture the output from the streamwriter
writer.Flush;
output = char(writer.Encoding.GetString(stream.ToArray));
%set the old Console back after done
Console.SetOut(oldConsole);
end
Save the above code as captureConsole.m and pass the method which calls System.out.Write to this function as follows:
>> NET.addAssembly('C:\work\MATLABWriter.dll');
>> writerObj = MATLABWriter.WriterClass;
% Instead of writerObj.Write
>> captureConsole('writerObj.Write')
ans =
Hello, world!