How do I call a .NET dll function from MATLAB?
조회 수: 45 (최근 30일)
이전 댓글 표시
I want to see how I can call a MATLAB-created .NET dll function from MATLAB, if it's possible at all.
I thought it would be straightforward, but I’m running into an error message.
Here’s what I did:
1. Created a test function
function out = myfunc1(inp)
out = 2*inp;
2. Compiled it into a .NET dll (using a APPS->APPLICATION COMPILER, etc with the option ‘Runtime included in package’ on): the dll name is myfunc1.dll and the class name is ClassName1
3. In the MATLAB command window, ran addAssembly to add this library
library = NET.addAssembly('[path to the created dll]\for_testing\myfunc1.dll');
4. Checked what methods it has (to make sure everything worked as expected)
methods myfunc1.ClassName1
Methods for class myfunc1.ClassName1:
ClassName1 Equals GetType WaitForFiguresToDie
Dispose GetHashCode ToString myfunc1
Static methods:
ReferenceEquals
so I could see that the method myfunc1 is there
5. Tried to instantiate an object of this class
obj = myfunc1.ClassName1;
(with the idea to later run the actual function: obj.myfunc1(inp);)
6. At the instantiation stage got the following error message
Message: The type initializer for 'myfunc1.ClassName1' threw an exception.
Source: mscorlib
HelpLink:
7. I tested the same dll in a C# project and it worked fine, so I don't think it's the same issue as https://www.mathworks.com/matlabcentral/answers/384932-why-do-i-get-type-initializer-throws-an-exception-error-every-time-the-compiled-class-is-instantia
Many thanks for any help!
댓글 수: 2
Guillaume
2019년 3월 6일
It could be the same issue.If your C# projec has the same bitness as the dll, then you won't see an error there. But if that bitness is not the same as matlab, yes, you'd get an error in matlab.
I don't have matlab Compiler so don't know, but isn't there a setting in your matlab project for the target platform? If it's set to 32-bit (or any) and assuming that you're using 64-bit matlab, then you will get an error.
채택된 답변
Guillaume
2019년 3월 6일
While looking for a setting to configure the bitness in the online documentation, I came across these prerequisites:
.NET assemblies or DLLs built with MATLAB Compiler SDK cannot be loaded back into MATLAB with the .NET External Interface method addAssembly.
So, looks like what you're trying to do is not supported and is never going to work. Admittedly, it's an odd thing to want to do. Why not use the m file directly?
추가 답변 (1개)
Rajeev Yadav
2021년 9월 21일
Why not??? Matlab license are so expensive that we have to look for solutions like this or completely abandon matlab and that's what is gonna happen in coming years ...
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 .NET Assembly Integration에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!