简体   繁体   English

如何在已编译的.NET程序集中使用Matlab对象?

[英]How can I use Matlab objects in compiled .NET assemblies?

I have a basic Matlab class which I want to instantiate in C#. 我有一个基本的Matlab类,我想在C#中实例化。

classdef MyClass
    properties
        Value
    end

    methods
        function obj=MyClass(v)
            obj.Value = v;
        end

        function display(obj)
            disp(obj.Value);
        end
    end    
end

This is then built into a .DLL file and imported in a C# project along with the associated Matlab namespaces (MathWorks.MATLAB.NET.Arrays, MathWorks.MATLAB.NET.Utility). 然后将其内置到.DLL文件中,并与关联的Matlab命名空间(MathWorks.MATLAB.NET.Arrays,MathWorks.MATLAB.NET.Utility)一起导入C#项目中。

On the C# side, I am trying to build an instantiation of this class thus: 在C#端,我正在尝试构建此类的实例:

        Untitled2.MLTestClass matlab = new Untitled2.MLTestClass();
        MWCharArray input = new MWCharArray("Initial");                       
        MWArray[] result = matlab.MyClass(1, input);

By the end of the last line of code, result.Length = 1 and result[0] = null. 在代码的最后一行末尾,result.Length = 1并且result [0] = null。 I was somehow expecting to obtain the reference to the newly created Matlab object somehow. 我以某种方式期望获得对新创建的Matlab对象的引用。 I was wondering, is this even possible? 我在想,这有可能吗? And if yes, then how can this be accomplished? 如果是的话,那如何实现呢? If no, is there a way around it? 如果没有,有没有办法解决? (I basically have a GUI component written in C# which I don't want to integrate in Matlab, but rather, the other way round). (我基本上有一个用C#编写的GUI组件,但我不想集成到Matlab中,反之亦然)。

It is not possible to use Matlab classes inside .NET assemblies. .NET程序集中不能使用Matlab类。 There are numerous workarounds: 有许多解决方法:

  1. Define your variable as global , and access it with several functions that wrap its methods 将变量定义为global ,并使用几个包装其方法的函数进行访问
  2. Return your Matlab class as a value of field in struct. 返回您的Matlab类作为struct中field的值。

Here is a code snippet for (1): 这是(1)的代码段:

function CreateMyClass(st)
    global myClass;
    myClass = MyClass(st);
end

function DisplayMyClass()
    global myClass;
    myClass.display();
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM