简体   繁体   中英

How to create a .net assembly in C#, which can be consumed by MATLAB?

I am writing a .net assembly in c# using Visual Studio 2022:

using System;

namespace ClassLibrary1
{
    public class Class1
    {
        public int f(int i) { return 3 * i; }
    }
}

When I try to load it into MATLAB using the following script:

try
  NET.addAssembly(fullfile(pwd, "ClassLibrary1.dll"));
catch ex
end

ex.ExceptionObject.LoaderExceptions.Get(0).Message  

I get the error message:

Die Datei oder Assembly "System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" oder eine Abhängigkeit davon wurde nicht gefunden. Das System kann die angegebene Datei nicht finden.

I don't know exactly what the english wording is, something like

Could not load file or assembly "System.Runtime....

The dll-file was locked by MATLAB after this.

I tried creating the assembly using .NET 6.0 as well as .NET core 3.1 in combination with MATLAB 2021b and 2022a, all with the same error message. Just for .NET core, the missing assembly version was

System.Runtime, Version=4.2.2.0

I also tried to consume the assembly with c# console programs, which worked without issues.

It appears that Matlab does not offer support for modern .NET runtimes. According to the documentation (already linked by @MiB_Coder) Matlab supports '.NET Framework Version 4.0 and above'. This means the TargetFramework property in your .csproj file must correspond to CRL (runtime) 4 ( https://en.wikipedia.org/wiki/.NET_Framework_version_history ).

This also means you can't use any C# code compiled for .NET Core, or .NET 5/6/7. This means that you are limited to C# <= 7.3 You should, however, be able to summon the class shown in the OP if it is compiled compiled using .NET Framework <= 4.8, or .NET Standard <= 2.0. I compiled using .NET Framework 4.5 and .NET Standard 2.0 and both loaded into Matlab just fine.

A couple of comments:

  1. Mathworks should update their support for newer and more universal .NET Runtimes. .NET Framework is a Windows-only version of .NET, but the fact that I was able to use code compiled against .NET Standard 2.0 tells me there is some hope that that version could be used on other OSs, but according to the documentation page only Windows is supported.

  2. According to Microsoft , .NET Standard 2.1 (which I don't currently have installed) supports C# <= 8.0, so if this works in Matlab interop, you will at least have some of the nice features that came in with 8.0 ( using statements, nullable reference types, etc.).

  3. To install CRL 4, you need to install a .NET SDK corresponding to this release. The developer packs and runtimes are available for download here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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