Simulink: how to call .NET static methods properties and instance constructo​rs/propert​ies.method​s through matlab user function blocks? And how to pass those values from one to block another one

1 view (last 30 days)
Hi,
I'm looking for a way to make proper .NET calls from Simulink through matlab. I'm pretty aware that this code is not going to be compiled and therefore only interpreted on the matlab side. Also, I'm wondering how can I pass some reference values through one block to another one.
According to this reference: Using .NET properties in matlab I can see how it works on matlab:
NET.addAssembly('System.Speech');
obj = System.Speech.Synthesis.SpeechSynthesizer;
obj.Volume = 50;
Speak(obj,'You can use .NET Libraries in MATLAB')
The problem is that, for instance, this code is not really usable as such as it is in a Simulink matlab user-function block, I need to use whether code.extrinsic or feval .
I successfully managed to use feval and coder.extrinsic for callings methods but I cannot find a way to get or set the values on properties such as:
function speechSynthesizer = Initialize()
%#codegen
feval('clc');
feval('clear');
feval('NET.addAssembly', 'System.Speech');
speechSynthesizer = feval('System.Speech.Synthesis.SpeechSynthesizer');
volume = speechSynthesizer.Volume;
speechSynthesizer.Volume = volume / 2;
feval('Speak', speechSynthesizer, 'Im using .NET from simulink');
Also I do not really now how to pass the speechSynthesizer as the return value since the matlab function block is quite restrictive.
Any idea / workaround to make it work?

Accepted Answer

Ryan Livingston
Ryan Livingston on 15 Jan 2015
I would write wrapper MATLAB functions that do the work with your .NET objects and then call those wrappers extrinsically:
function obj = netSpeak
NET.addAssembly('System.Speech');
obj = System.Speech.Synthesis.SpeechSynthesizer;
obj.Volume = 50;
Speak(obj,'You can use .NET Libraries in MATLAB')
function block:
function Initialize()
%#codegen
coder.extrinsic('netSpeak');
netSpeak();
That way, you don't need to worry about using extrinsics to do complicated things like getting/setting properties.
As for passing data between the function blocks, you could have a function that maintains a persistent SpeechSynthesizer and provides it on request:
function syn = instance
persistent obj;
if isempty(obj)
NET.addAssembly('System.Speech');
obj = System.Speech.Synthesis.SpeechSynthesizer;
end
syn = obj;
In your wrapper functions just call instance to get access to your synthesizer. That effectively keeps the .NET data out of Simulink by letting MATLAB work with it.

More Answers (0)

Categories

Find more on Simulink Functions in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!