主要内容

MathWorks.MATLAB.Runtime.MATLABRuntime

表示 MATLAB Runtime 实例的 .NET 类

自 R2022b 起

描述

MATLABRuntime 类表示 MATLAB® Runtime 实例。您可以使用圆点表示法将 MATLAB 函数作为 MATLABRuntime 对象的方法进行调用,因为这些函数在您调用它们时会动态调用。

程序集

C:\Program Files\MATLAB\R2025b\extern\dotnet\netstandard2.0\MathWorks.MATLAB.Runtime.dll

C:\Program Files\MATLAB\R2025b\extern\dotnet\netstandard2.0\MathWorks.MATLAB.Types.dll

类详细信息

命名空间:

MathWorks.MATLAB.Runtime
超类:System.Dynamic.DynamicObject
接口:System.IDisposable

方法摘要

静态方法

StartMATLAB

同步启动 MATLAB Runtime 实例

StartMATLABAsync

异步启动 MATLAB Runtime 实例

TerminateApplication

终止 MATLAB 应用程序

SetupMacRunLoopAndRun

为在 macOS 上运行的应用程序设置 Core Foundation CFRunLoop

实例方法

WaitForFiguresToClose

暂停,直到程序集中的所有图窗均已关闭

Dispose

显式终止 MATLAB Runtime 实例

方法详细信息

StartMATLAB

static MATLABRuntime StartMATLAB(string ctfArchiveName);

描述

同步启动 MATLAB Runtime 实例并连接到它。如果希望在一个单独的进程中启动 MATLAB Runtime 实例,请将 OutOfProcessAttribute 设置为 true

参数

string ctfArchiveName

可部署存档(.ctf 文件)的名称。

返回

MATLABRuntime 的实例。

抛出

MathWorks.MATLAB.Exceptions.MATLABNotAvailableException

MATLAB 启动失败。

System.ArgumentNullException空字符串不是有效参量。
C# 示例

使用可部署存档(.ctf 文件)启动一个新的 MATLAB Runtime 实例。

using System;
using MathWorks.MATLAB.Runtime;
using MathWorks.MATLAB.Types;

namespace MyConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string ctfPath = @"P:\MATLAB\work\mylinspace.ctf ";
            using (dynamic matlab = MATLABRuntime.StartMATLAB(ctfPath))
            {
                double[] vec = matlab.mylinspace(1.0, 100.0);
                foreach (double i in vec)
                {
                    Console.Write("{0} ", i);
                }
            }
            Console.ReadLine();
        }
    }
}

StartMATLABAsync

static Task<MATLABRuntime> StartMATLABAsync(string ctfArchiveName);

static Task<MATLABRuntime> StartMATLABAsync(string ctfArchiveName, System.Threading.CancellationToken token);

描述

在一个单独的进程中异步启动 MATLAB Runtime 实例并连接到它。

参数

string ctfArchiveName

可部署存档(.ctf 文件)的名称。

CancellationToken token

用来取消异步任务的取消令牌。默认值为 System.Threading.CancellationToken.None

返回

MATLABRuntime 实例被初始化或发生异常时完成的任务。

抛出

MathWorks.MATLAB.Exceptions.MATLABNotAvailableException

MATLAB 启动失败。

System.ArgumentNullException空字符串不是有效参量。
C# 示例

异步启动两个 MATLAB Runtime 实例。

using System;
using MathWorks.MATLAB.Runtime;
using MathWorks.MATLAB.Types;

// Set OutOfProcessAttribute to true
// This ensures each MATLAB Runtime instance runs in a separate process, allowing for true parallel execution
[assembly: OutOfProcess(true)]

namespace MyConsoleApp
{
    class Program
    {
        // Asynchronously calls a MATLAB function when the MATLAB Runtime instance is ready
        static async void CallDisp(Task<MATLABRuntime> matlabTask)
        {
            try
            {
                // Await the completion of the MATLAB Runtime startup
                dynamic matlab = await matlabTask;

                // Use the MATLAB instance within a using statement to ensure proper disposal
                using (matlab)
                {
                    // Call a MATLAB function with specified arguments
                    matlab.mydisp(new RunOptions(nargout: 0), "Hello, Call MATLAB!");
                }
            }
            catch (Exception ex)
            {
                // Handle any exceptions that occur during the MATLAB function call
                Console.WriteLine($"Error in MATLAB call: {ex.Message}");
                throw;
            }
        }

        static void Main(string[] args)
        {
            try
            {
                // Start two MATLAB Runtime instances asynchronously
                // Each instance will execute the CallDisp method upon startup completion
                Task workflowTask1 = MATLABRuntime.StartMATLABAsync("mydisp.ctf").ContinueWith(CallDisp);
                Task workflowTask2 = MATLABRuntime.StartMATLABAsync("mydisp.ctf").ContinueWith(CallDisp);

                // Wait for both MATLAB Runtime instances to complete their tasks
                // This ensures that the main thread does not proceed until both instances are done
                Task.WhenAll(workflowTask1, workflowTask2).Wait();
                Console.WriteLine("Done!");
            }
            catch (AggregateException ae)
            {
                // Handle exceptions that are thrown from within the tasks
                // Rethrow the inner exception for further handling or logging
                throw ae.InnerException;
            }
        }
    }
}

异步启动一个 MATLAB Runtime 实例,但如果操作花费的时间超过 10 秒则取消。

using System;
using System.Threading;
using System.Threading.Tasks;
using MathWorks.MATLAB.Runtime;
using MathWorks.MATLAB.Types;

class Program
{
    static async Task CallMATLAB(Task<MATLABRuntime> matlabTask)
    {
        try
        {
            // Await the MATLAB Runtime task to complete and get the MATLAB instance
            using (dynamic matlab = await matlabTask)
            {
                // Call a MATLAB function using the MATLAB instance
                matlab.mydisp(new RunOptions(nargout: 0), "Hello, CallMATLAB!");
            }
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("MATLAB call was cancelled.");
            throw; // Re-throwing to be caught in the calling method
        }
    }

    static async Task Main(string[] args)
    {
        // Create a CancellationTokenSource to control task cancellation
        using (CancellationTokenSource src = new CancellationTokenSource())
        {
            // Schedule the cancellation after 10 seconds
            src.CancelAfter(TimeSpan.FromSeconds(10));

            try
            {
                // Start the MATLAB Runtime asynchronously with cancellation token
                Task workflowTask = MATLABRuntime.StartMATLABAsync("mydisp.ctf", src.Token)
                    .ContinueWith(CallMATLAB, src.Token);

                // Await the completion of the MATLAB Runtime task
                // This is a non-blocking wait and will throw an exception if cancelled
                await workflowTask;
                Console.WriteLine("Task completed successfully!");
            }
            catch (OperationCanceledException)
            {
                // Handle the cancellation of the task
                Console.Error.WriteLine("Task was cancelled before completion.");
            }
            catch (Exception ex)
            {
                // Handle any other exceptions that might occur
                Console.Error.WriteLine($"An error occurred: {ex.Message}");
                throw; // Optional: rethrow if you want to escalate the error
            }
        }
    }
}

TerminateApplication

static void TerminateApplication();

描述

终止 MATLAB 应用程序并拆除 MATLAB Runtime 实例。

C# 示例
using System;
using MathWorks.MATLAB.Runtime;
using MathWorks.MATLAB.Types;

namespace MyConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string ctfPath = @"P:\MATLAB\work\mylinspace.ctf ";
            dynamic matlab = MATLABRuntime.StartMATLAB(ctfPath);
            double[] dbls = matlab.mylinspace(1.0, 100.0);
            foreach (double i in dbls)
            {
                Console.Write("{0} ", i);
            }
            Console.ReadLine();
            MATLABRuntime.TerminateApplication();
        }
    }
}

SetupMacRunLoopAndRun

static void SetupMacRunLoopAndRun(Func<Object, int> userFunc, Object args);

描述

为在 macOS 上运行的应用程序设置 Core Foundation CFRunLoop。如果未指定 NojvmOutOfProcess 属性,请使用此方法。

参数

Func<Object, int> userFunc

用户指定的运行 MATLAB 代码的函数或方法,以 Object 作为参数,以 int 作为输出。

Object args

传递给用户指定的函数或方法的参量。

C# 示例
using System;
using MathWorks.MATLAB.Runtime;
using MathWorks.MATLAB.Types;
using MathWorks.MATLAB.Exceptions;
using System.Threading.Tasks;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Dynamic;
[assembly: RuntimeOption("-softwareopenglmesa")] 

namespace MyConsoleApp
{
  public class Program
  {
    static void Main(string[] args)
    {
        MATLABRuntime.SetupMacRunLoopAndRun(MainFunc, null);
    }
    static int MainFunc(Object args)
    {
      try 
      {
        string ctfPath = @"P:\MATLAB\work\matlabfunccomp.ctf ";
		using (dynamic matlab = MATLABRuntime.StartMATLAB(ctfPath))
        {
          matlab.myFun(new RunOptions(nargout: 0), "all");
        }
      } 
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message + DateTime.Now.ToLongTimeString());
      }
      Thread.Sleep(100);
      Console.WriteLine("Terminating Application");
      MATLABRuntime.TerminateApplication();
      return 0;
    }
  }
}

WaitForFiguresToClose

void WaitForFiguresToClose();

描述

在继续执行之前,等待由 MATLAB Runtime 实例创建的所有可见图窗关闭。

C# 示例
using System;
using MathWorks.MATLAB.Runtime;
using MathWorks.MATLAB.Types;

namespace MyConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string ctfPath = @"P:\MATLAB\work\myPlot.ctf ";
            using (dynamic matlab = MATLABRuntime.StartMATLAB(ctfPath))
            {
                matlab.myPlot(new RunOptions(nargout: 0), 10.0);
                matlab.WaitForFiguresToClose();
            }
        }
    }
}

Dispose

void Dispose();

描述

显式终止 MATLAB Runtime 实例。如果未被调用,则 MATLAB Runtime 实例将由 TerminateApplication 方法终止。

抛出

MathWorks.MATLAB.Exceptions.MATLABExecutionException

MATLAB 终止失败。

C# 示例
using System;
using MathWorks.MATLAB.Runtime;
using MathWorks.MATLAB.Types;

namespace MyConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string ctfPath = @"P:\MATLAB\work\dotnetnew\output\mylinspace.ctf ";
            dynamic matlab = MATLABRuntime.StartMATLAB(ctfPath);
            double[] vec = matlab.mylinspace(1.0, 100.0);
            foreach (double i in vec)
            {
                Console.Write("{0} ", i);
            }
            matlab.Dispose();
        }
    }
}

版本历史记录

在 R2022b 中推出