| Contents | Index |
In the .NET Framework, a delegate is a type that defines a method signature. It lets you pass a function as a parameter. The use of delegates enables .NET applications to make calls into MATLAB callback functions or class instance methods. For the rules MATLAB uses to define the signature of a callback function or class method, see Reading Method Signatures in Using a .NET Object. For a complete description of delegates and when to use them, consult an outside resource, such as the Microsoft Developer Network.
There are three steps to using delegates:
Declaration — Your .NET application contains the declaration. You cannot declare a delegate in the MATLAB language.
Instantiation — In MATLAB, create an instance of the delegate and associate it with a specific MATLAB function or .NET object method.
Invocation — Call the function with specified input and output arguments. Use the delegate name in place of the function name.
This example shows you how to use a delegate in MATLAB. It creates a delegate using a MATLAB function (char). For another example, see Create a Delegate from a .NET Object Method.
This example consists of the following tasks:
The following C# statements declare a delegate, delInteger, which encapsulates any method that takes an integer input and returns a string. You need to build the assembly NetDocDelegate in order to run these examples. For information, see Building a .NET Application for MATLAB Examples.
If the NetDocDelegate assembly is in your c:\work folder, load the file with the command:
dllPath = fullfile('c:','work','NetDocDelegate.dll');
NET.addAssembly(dllPath);
The MATLAB char function, which converts a nonnegative integer into a character array (string), has a signature that matches the delInteger delegate. For example, the following command displays the ! character:
char(33)
To create an instance of the delInteger delegate, pass the function handle of the char function:
myFunction = NetDocDelegate.delInteger(@char);
Use myFunction the same as you would char. For example, the following command displays the ! character:
myFunction(33)
The following C# class defines the methods AddEggs and AddFlour, which have signatures matching the delInteger delegate:
Build the Recipe assembly, and then load it and create a delegate myFunc using AddEggs as the callback:
NET.addAssembly(dllPath);
NET.addAssembly('c:\work\Recipe.dll');
obj = Recipe.MyClass;
myFunc = NetDocDelegate.delInteger(@obj.AddEggs);
myFunc(2)MATLAB displays:
ans = Add 2 eggs
For a C# delegate defined as:
namespace MyNamespace
{
public delegate void MyDelegate();
}
MATLAB creates the following constructor signature.
| Return Type | Name | Arguments |
|---|---|---|
| MyNamespace.MyDelegate obj | MyDelegate | (target, |
| string methodName) |
The argument target is one of the following:
An instance of the invocation target object when binding to the instance method
A string with fully qualified .NET class name when binding to a static method
methodName is a string specifying the callback method name.
For the following C# delegate and class definition:
namespace MyNamespace
{
public delegate void MyDelegate();
public class MyClass
{
public void MyMethod(){}
}
}To instantiate the delegate in MATLAB, type:
targetObj = MyNamespace.MyClass(); delegateObj = MyNamespace.MyDelegate(targetObj, 'MyMethod');
For the following C# delegate and class definition:
namespace MyNamespace
{
public delegate void MyDelegate();
public class MyClass
{
public static void MyStaticMethod(){}
}
}To instantiate the delegate in MATLAB, type:
delegateObj=MyNamespace.MyDelegate(... 'MyNamespace.MyClass','MyStaticMethod');
The MATLAB rules for mapping out and ref types for delegates are the same as for methods. See C# Method Access Modifiers.
For example, the following C# statement declares a delegate with a ref argument:
public delegate void delref(ref Double refArg);
The signature for an equivalent MATLAB delegate function maps refArg as both RHS and LHS arguments:
function refArg = myFunc(refArg)
The following C# statement declares a delegate with an out argument:
public delegate void delout(
Single argIn,
out Single argOut);The signature for an equivalent MATLAB delegate function maps argOut as an LHS argument:
function argOut = myFunc(argIn)
MATLAB provides the instance method Combine, that lets you combine a series of delegates into a single delegate. The Remove and RemoveAll methods delete individual delegates. For more information, refer to the .NET Framework Class Library, as described in To Learn More About the .NET Framework.
For example, create the following MATLAB functions to use with the NetDocDelegate.delInteger delegate:
function out = action1(n) out = 'Add flour'; disp(out); end
function out = action2(n) out = 'Add eggs'; disp(out); end
Create delegates step1 and step2:
step1 = NetDocDelegate.delInteger(@action1); step2 = NetDocDelegate.delInteger(@action2);
To combine into a new delegate, mixItems, type:
mixItems = step1.Combine(step2);
Or, type:
mixItems = step1.Combine(@action2);
Invoke mixItems:
result = mixItems(1);
In this case, the function action2 follows action1:
Add flour Add eggs
The value of result is the output from the final delegate (step2).
result = Add eggs
You also can use the System.Delegate class static methods, Combine, Remove and RemoveAll.
To remove a step1 from mixItems, type:
step3 = mixItems.Remove(step1);
It is possible to call a synchronous method asynchronously in MATLAB. With some modifications, you can use the Microsoft BeginInvoke and EndInvoke methods. For more information, refer to the MSDN article " Calling Synchronous Methods Asynchronously " at http://msdn.microsoft.
You can use delegates to call a synchronous method asynchronously by using the BeginInvoke and EndInvoke methods. If the thread that initiates the asynchronous call does not need to be the thread that processes the results, you can execute a callback method when the call completes. For information about using a callback method, see Calling a Method Asynchronously Using a Callback When an Asynchronous Call Finishes.
Note MATLAB is a single-threaded application. Therefore, handling asynchronous calls in the MATLAB environment might result in deadlocks. |
You can execute a callback method when an asynchronous call completes. A callback method executes on a different thread than the thread that processes the results of the asynchronous call.
The following is an overview of the procedure. If you do not use a callback function, follow the procedure in Calling a Method Asynchronously Without a Callback.
Select or create a MATLAB function to execute asynchronously.
Select or create a C# delegate and associate it with the MATLAB function.
Create a MATLAB callback function with a System.AsyncCallback Delegate delegate signature. The signature, shown at the MSDN Web site, is:
public delegate void AsyncCallback(IAsyncResult ar)
Using MATLAB code, initiate the asynchronous call using the BeginInvoke method, specifying the callback delegate and, if required, object parameters.
Continue executing commands in MATLAB.
When the asynchronous function completes, MATLAB calls the callback function, which executes the EndInvoke method to retrieve the results.
Callback Example. In this example, create the following MATLAB function to execute asynchronously:
function X = DivideFunction(A, B)
if B ~= 0
X = A / B;
else
errid = 'MyID:DivideFunction:DivisionByZero';
error(errid, 'Division by 0 not allowed.');
end
end
Create the following MATLAB function, which will execute as the callback when the asynchronous method invocation completes. This function displays the result value of the EndInvoke method.
function myCallback(asyncRes) result = asyncRes.AsyncDelegate.EndInvoke(asyncRes); disp(result); end
Use the del2Integer delegate, defined in the NetDocDelegate assembly:
public delegate Int32 del2Integer(Int32 arg1, Int32 arg2);
Run the example:
% Create the delegate divDel = NetDocDelegate.del2Integer(@DivideFunction); A=10; B=5; % Initiate the asynchronous call. asyncRes = divDel.BeginInvoke(A,B,@myCallback,[]);
MATLAB displays the result: 2
The following is an overview of the procedure. If you want to use a callback function, follow the procedure in Calling a Method Asynchronously Using a Callback When an Asynchronous Call Finishes.
Select or create a MATLAB function to execute asynchronously.
Select or create a C# delegate and associate it with the MATLAB function.
In MATLAB, initiate the asynchronous call using the BeginInvoke method.
Continue executing commands in MATLAB.
Poll for asynchronous call completion using the MATLAB pause function.
When the asynchronous function completes, call the EndInvoke method to retrieve the results.
Example Without Callback. In this example, create the following MATLAB function, myFunction:
% MATLAB function to execute asynchrounously function res = myFunction(strValue) res = strValue; end
Use the delString delegate, defined in the NetDocDelegate assembly:
public delegate string delString(string message);
In MATLAB, create the delegate, myDelegate, define the input values, and start the asynchronous call:
myDelegate = NetDocDelegate.delString(@myFunction); A='Hello'; asyncRes = myDelegate.BeginInvoke(A,[],[]);
The BeginInvoke method returns the object, asyncRes, which you use to monitor the progress of the asynchronous call. Poll for results, using the MATLAB pause function to let MATLAB process the events:
while asyncRes.IsCompleted ~= true
pause(0.01);
end
Retrieve and display the results of the asynchronous call:
result = myDelegate.EndInvoke(asyncRes); disp(result)
MATLAB displays:
Hello
The MATLAB delegate signature for EndInvoke follows special mapping rules if your delegate has out or ref type arguments. For information about the mapping, see Use .NET Delegates With the out and ref Type Arguments. For examples, see the EndInvoke reference page.
For MATLAB to process the event that executes the delegate's callback on the main thread, you must call the MATLAB pause (or a similar) function.
MATLAB does not support associating a delegate instance with a generic .NET method.
When calling a method asynchronously, use the technique described in Calling a Method Asynchronously Without a Callback. Be aware that:
MATLAB is a single-threaded application. Therefore, handling asynchronous calls in the MATLAB environment might result in deadlocks.
For the technique described in the MSDN topic , MATLAB does not support the use of the WaitOne() method overload with no arguments.
You cannot call EndInvoke to wait for the asynchronous call to complete.
![]() | Using Arrays with .NET Applications | .NET Enumerations in MATLAB | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A; sessions led by MATLAB experts.
| © 1984-2011- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |