大家好,我正在尝试从 C# 应用程序控制 Matlab,所以我选择了 COM 服务器解决方案,但是我无法让它工作。
首先,我使用comserver('register','User','all')Matlab 命令窗口将我的 Matlab 注册为 COM 服务器。然后我在我的 C# 项目中引用了这个服务器。
之后,我实现了简单的 C# 代码来访问我编写的 Matlab 函数:
// Create the MATLAB instance
MLApp.MLApp matlab = new MLApp.MLApp(); // Where the code returns an error
// Change to the directory where the function is located
matlab.Execute(@"cd C:\Users\jar\Downloads\");
// Define the output
object result = null;
// Call the MATLAB function myfunc
matlab.Feval("traj2D_image",1, out result,
ParametresBalayage.NomFichier,
ParametresBalayage.LongueurBalayage,
ParametresBalayage.NbBalayage,
ParametresBalayage.PasBalayage,
ParametresBalayage.DecalageBalayage,
ParametresBalayage.DecalageStries,
ParametresBalayage.Vitesse,
sens);
// Display result
object[] res = result as object[];
Run Code Online (Sandbox Code Playgroud)
但是当我尝试创建 MATLAB 实例时出现此错误:
System.InvalidCastException : 'Unable to cast a COM object of type 'System.__ComObject' into interface type 'MLApp.MLApp'. This operation failed, because calling QueryInterface on the COM component for the interface with the IID '{669CEC93-6E22-11CF-A4D6-00A024583C19}' has failed because of the following error : Unspecified error (HRESULT Exception : 0x80004005 (E_FAIL)).'
Run Code Online (Sandbox Code Playgroud)
这很奇怪,因为创建了 Matlab 实例,打开了一个新的 Matlab 命令窗口,但代码没有继续前进并停止。
有谁知道为什么我有这个问题?先感谢您。
编辑:尝试另一种方法
我一步一步地遵循 MathWorks 的说明,但在创建MLApp实例时它仍然给我同样的错误,所以我尝试探索其他选项,例如手动注册、注销或查询 MATLAB COM 服务器,但没有任何改变。我仍然希望第一个选项起作用,但我去看了其他 .NET 语言以了解它们是如何实现的。
因此,我正在尝试在 VB.NET 中找到的另一种方法,该方法适用于 excel VBA 模块:键入 mlType;对象matlab;
mlType = Type.GetTypeFromProgID("Matlab.Application");
matlab = Activator.CreateInstance(mlType);
Console.WriteLine(matlab.???("surf(peaks)")); // what do i have to put here?
Run Code Online (Sandbox Code Playgroud)
这会创建一个 MAtlab 实例而不返回任何错误,但是在 VB.NETExecute中,对象中有一个类,我在这里没有,所以我尝试了matlab.Equals("surf(peaks)")(这显然不是正确的方法),但我不知道该放什么让实例做我想做的事。
| 归档时间: |
|
| 查看次数: |
148 次 |
| 最近记录: |