How can I have System.Console.WriteLine write to the MATLAB command window while using the .NET API in MATLAB 7.8 (R2009a)?
6 次查看(过去 30 天)
显示 更早的评论
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?
采纳的回答
MathWorks Support Team
2010-3-16
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!
0 个评论
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!