主要内容

通过 C# 客户端调用 MATLAB 函数

R2026b

注意

要在 MATLAB® R2022b 或更高版本中从 C# 应用程序调用 MATLAB 函数,请考虑使用 MATLAB Engine API for .NET。有关详细信息,请参阅从 .NET 调用 MATLAB。有关示例,请参阅从 .NET 执行 MATLAB 函数。

如果您需要维护为 MATLAB R2022a 或更早版本创建的现有程序,请使用此示例,此示例说明如何使用 MATLAB 作为 COM 自动化服务器从 C# 应用程序调用用户定义的 MATLAB 函数 myfunc。该示例使用先前绑定的特定 MATLAB 版本。

注意

要使用此示例,您必须知道如何在开发环境(如 Microsoft® Visual Studio®)中创建和运行 COM 控制台应用程序。

在文件夹 c:\temp\example 中创建 MATLAB 函数 myfunc。

function [x,y] = myfunc(a,b,c) 
x = a + b; 
y = sprintf('Hello %s',c); 

在您的开发环境中创建 C# 控制台应用程序。在 C# 中引用 MATLAB 类型库的语句如下:

MLApp.MLApp matlab = new MLApp.MLApp();

以下是完整示例:

using System; 
using System.Collections.Generic; 
using System.Text; 

namespace ConsoleApplication2 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            // Create the MATLAB instance 
            MLApp.MLApp matlab = new MLApp.MLApp(); 

            // Change to the directory where the function is located 
            matlab.Execute(@"cd c:\temp\example"); 

            // Define the output 
            object result = null; 

            // Call the MATLAB function myfunc
            matlab.Feval("myfunc", 2, out result, 3.14, 42.0, "world"); 
             
            // Display result 
            object[] res = result as object[]; 
             
            Console.WriteLine(res[0]); 
            Console.WriteLine(res[1]); 
            // Get user input to terminate program
            Console.ReadLine();
        } 
    } 
}

从 C# 客户端程序中,在您的工程中添加对 MATLAB COM 对象的引用。此引用将您的程序绑定到 MATLAB 的特定版本。有关详细信息,请参考您的供应商文档。例如,在 Microsoft Visual Studio 中,打开您的工程。在工程菜单中,选择添加引用。在“添加引用”对话框中,选择 COM 选项卡。选择 MATLAB 应用程序。

在开发环境中编译并运行该应用程序。

另请参阅

|

主题