Clear Filters
Clear Filters

Convert MWCharArray to MWStructArray

9 views (last 30 days)
Said Labreche
Said Labreche on 27 Apr 2022
Answered: SOUMNATH PAUL on 10 Nov 2023
Bonjour,
I have created a function in a Matlab DLL. I use this function, in C#, to create an output "Result" as MWArray. In C#, I transform easely "Result" to an an MWStructArray by MWStructArray Results_Bis = (MWStructArray)Result; this transformation works
Now, I modify my function. The output is not "Result" but "Result_JSon" an MWCharArray obtained by
Result_JSon = jsonencode(Result)
I try diffferent ways without success to create a same MWStructArray by using the new result "Result_JSon"
Can you please, help me ?
Thank you in advance
Best regards
Saïd Labrèche
sorry for my bad English

Answers (1)

SOUMNATH PAUL
SOUMNATH PAUL on 10 Nov 2023
Hi,
To my understanding, you initially had a MATLAB DLL function providing an MWArray output named “Result” convertible to MWStructArray in C#. The function was later modified to yield “Result_JSon, an MWCharArray which you obtained through JSON encoding. You want to convert the MWCharArray back into MWStructArray format in C#.
You can follow below mentioned steps for the proper conversion:
  1. Update MATLAB Function: Make sure your MATLAB function now generates a JSON string(‘Result_JSon’) using the jsonencode’ function.
  2. Install Newtonsoft.Json: In your C# project, install the Newtonsoft.Json library using Nuget Package Manager.
  3. De-serialize JSON String: Deserialize the JSON string(‘Result_JSon) into a C# object using a nifty tool from Newtonsoft.Json.
  4. Convert to MWStructArray: Create a function to convert fields of the C# object to correct MWArray types and field names.
using MathWorks.MATLAB.NET.Arrays;
using Newtonsoft.Json;
MWArray Result;
MWCharArray Result_JSon = (MWCharArray)yourMatlabFunctionCall();
// Step 1: Convert MWCharArray to C# string
string jsonString = Result_JSon.ToString();
// Step 2: Deserialize JSON string into C# object
YourCSharpObjectType resultObject = JsonConvert.DeserializeObject<YourCSharpObjectType>(jsonString);
// Step 3: Convert C# object to MWStructArray
MWStructArray Results_Bis = ConvertToMWStructArray(resultObject);
// Your ConvertToMWStructArray function
MWStructArray ConvertToMWStructArray(YourCSharpObjectType resultObject)
{
// Create a new MWStructArray
MWStructArray mwStructArray = new MWStructArray(1, 1);
// Customize the following based on your actual field names
// For each field, convert the C# value to the appropriate MWArray type
mwStructArray["FieldName1"] = new MWNumericArray(resultObject.Field1);
mwStructArray["FieldName2"] = new MWCharArray(resultObject.Field2);
// ...
return mwStructArray;
}
You can find more information in the following link:
Hope it helps!
Regards,
Soumanth

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!