Why do invalid cast exceptions occur when executing MATLAB R2022b functions from Visual Basic .NET applications?
7 次查看(过去 30 天)
显示 更早的评论
MathWorks Support Team
2023-3-7
回答: MathWorks Support Team
2023-3-9
I am using the .NET class "MATLABEngine" to call MATLAB functions as methods from a Visual Basic .NET console app, as described in the documentation below:
I'm able to get the expected output shown in the Visual Basic .NET example for the "StartMATLAB" method, which starts a new MATLAB process with default options.
However, when I add the following lines of code that call the "magic" MATLAB function to the Visual Basic .NET example code:
Dim xIn As Double = 5.0
Dim results(,) As Double
results = matlab.magic(xIn)
I receive an invalid cast exception as shown below:
Unhandled exception. System.InvalidCastException: Unable to cast object of type 'MathWorks.MATLAB.Types.FevalTaskResult' to type 'System.Double[,]'.
at <NAME OF CONSOLE APP>.Program.Main() in <PATH TO PROGRAM FILE CONTAINING EXAMPLE CODE>:<LINE 3 FROM EXAMPLE CODE>
I would like to resolve this error to get a better understanding of building Visual Basic .NET console apps that leverage MATLAB functions.
采纳的回答
MathWorks Support Team
2023-3-7
In Visual Basic .NET, you have to use the "CTypeDynamic" method to convert variables of dynamic type (e.g. the return of "matlab.magic()") to a known type (e.g. Double(,)). For more information regarding the "CTypeDynamic" method, take a look at Microsoft's documentation linked below:
For example, modify the line:
results = matlab.magic(xIn)
To:
results = CTypeDynamic(matlab.magic(xIn), GetType(Double(,)))
As of R2022b, this is necessary for writing Visual Basic .NET code due to dynamic typing, and unfortunately there is no way to make the code less verbose at this time. A code example is attached with the file "Program.vb".
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Call MATLAB from .NET 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!