非矩阵数据类型的 C# 和 MATLAB 互操作性

标签 c# matlab interop matlab-deployment

我正在编写一个需要调用 MATLAB 处理例程的 C# 程序。我一直在看 MATLAB 的 COM 接口(interface)。不幸的是,COM 接口(interface)在可以交换的数据类型方面似乎相当有限。支持矩阵和字符数组,但似乎不支持使用 COM 接口(interface)在 C# 和 MATLAB 之间交换结构数据或元胞数组。例如,在以下代码中(假设名为 IM000000 的 DICOM 图像存在于相应的文件夹中),MATLAB 变量“img”和“header”分别是一个 256x256 int16 矩阵和一个结构。 GetWorkspaceData 调用对“img”工作正常,但对“header”返回 null,因为“header”是一个结构。

public class MatlabDataBridge
{
   MLApp.MLAppClass matlab;

   public MatlabDataBridge()
   {
      matlab = new MLApp.MLAppClass();
   }

   public void ExchangeData()
   {
      matlab.Execute(@"cd 'F:\Research Data\'");
      matlab.Execute(@"img = dicomread('IM000000');");
      matlab.Execute(@"header = dicominfo('IM000000');");

      matlab.GetWorkspaceData(@"img", "base", out theImg);   // correctly returns a 2D array
      matlab.GetWorkspaceData(@"header", "base", out theHeader);   // fails, theHeader is still null

   }  
}

是否有合适的解决方法来使用 COM 接口(interface)将结构数据编码到 MATLAB 或从中编码?如果没有,MATLAB Builder NE 插件是否很好地支持此功能?

最佳答案

我最终使用 MATLAB Builder NE 插件解决了这个问题。代码最终看起来像这样:

using MathWorks.MATLAB.NET.Arrays;
using MathWorks.MATLAB.NET.Utility;
using MyCompiledMatlabPackage;   // wrapper class named MyMatlabWrapper is here

...


matlab = new MyMatlabWrapper();

MWStructArray foo = new MWStructArray(1, 1, new string[] { "field1", "field2" });
foo["field1", 1] = "some data";
foo["field2", 1] = 5.7389;

MWCellArray bar = new MWCellArray(1, 3);
bar[1, 1] = foo;
bar[1, 2] = "The quick brown fox jumped over the lazy dog.";
bar[1, 3] = 7.9;

MWArray result[];
result = matlab.MyFunction(foo, bar);

// Test the result to figure out what kind of data it is and then cast
// it to the appropriate MWArray subclass to extract and use the data

关于非矩阵数据类型的 C# 和 MATLAB 互操作性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5226631/

相关文章:

c# - 可空变量在内存分配中的优势 C#

c# - 在不同 UI 线程上创建的 WPF Access 窗口

c# - 使用 C# 测试字符串是否包含在 [brackets] 中的正则表达式

MATLAB – 对数运算错误

.net - 无法找到入口点 (cpp)

c# - 当缺少所有表达式时,C# for 循环会做什么。例如 (;;) {}

matlab - 拉格朗日插值法

matlab - 向量的最大值

c# - 将 C# 字符串作为参数发送到非托管 C++ DLL 函数

python - 是否有任何项目/库集可以轻松地在各种编程语言/平台之间进行通信?