Passing MATLAB methods as delegates to .NET Object

2019-06-01 06:52发布

问题:

Currently I have a MATLAB project using a .NET library. In Matlab I read in the .dll and instantiate a .NET object that I developed, and pass data to and from it:

NET.addAssembly('myLibrary.dll');
myNetObj = myNamespace.MyClass();
myNetObj.DoWork(someMatlabVariable);

Following the MATLAB documentation (See here) I can pass variables to my .NET functions, but I would like to have my .NET code call matlab methods/callbacks. The documentation clearly defines how to use .NET delegates MATLAB to .NET Delegates (See here).

Is it possible to pass (point to) a MATLAB function as a .NET Delegate or Action, so I can call the callback from my .NET object?

回答1:

I found how to pass Matlab function handles to delegates in c#. The answer is buried in the MATLAB .NET Documentation.

In .NET/C# code:

namespace SomeNamespace{
   // Create Delegate with appropriate input parameters and return types
   public Delegate void SomeDelegateType();

   public class SomeClass{
      // Create a Delegate for Matlab to assign to
      public SomeDelegateType SomeDelegate;
      ...
   }
}

In Matlab:

// % Instantiate .NET object    
classInstance = SomeNamespace.SomeClass();
// % Assign matlab function handle to .NET Delegate
classInstance.SomeDelegate = SomeNamespace.SomeDelegateType(@SomeMatlabMethod);

function SomeMatlabMethod()
   ...
end

Now when the .NET code calls SomeDelegate() it will call the Matlab function SomeMatlabMethod() handle passed to it.