Coping array from matlab to C#/.NET array

10 views (last 30 days)
Alaster Meehan
Alaster Meehan on 21 Aug 2023
Answered: Animesh on 31 Aug 2023
I have a dll from C# that i'm interfacing with. It has a structure that contains an array that I need to put data into.
This sets up the two arrays, in my actual problem the "destination" variable is in a structure but it shouldn't matter in this example.
MatArray = [1:10];
MatArray = int32(MatArray);
destination = NET.createArray('System.Int32', 10);
This can be copied item by item but for any decent size array this takes a long time.
% slow
for j = 1:numel(MatArray)
destination(j) = MatArray(j);
end
A faster way but a bit ulgy is to make a temp jaggered array then copy the data using a System.Array.Copy. This will also use up unnecessary memory, which may become an issue for very large arrays.
% fast but ulgy
temp = NET.createArray('System.Int32[]', 10);
temp(1) = MatArray;
System.Array.Copy(temp(1),destination,10);
Is there a better way to copy data from a matlab array into a c# array?

Answers (1)

Animesh
Animesh on 31 Aug 2023
I understand that you want to copy a matlab array to a C# array using MATLAB or C#.
You can try to use the ToArray method provided by the MATLAB int32 array to convert it to a regular C# array, and then assign it directly to the C# array.
Here is an example of how you can achieve this using C#:
// Assuming you have a C# array called "destination" and a MATLAB int32 array called "MatArray"
// Convert the MATLAB array to a C# array using the ToArray method
int[] temp = MatArray.ToArray();
// Copy the data from the temp array to the destination array
Array.Copy(temp, destination, temp.Length);
By using the ToArray method, you can directly convert the MATLAB array to a C# array without the need for intermediate steps or temporary arrays.
To read more about ToArray, please refer to the following documentation :- https://www.mathworks.com/help/dotnetbuilder/MWArrayAPI/html/M_MathWorks_MATLAB_NET_Arrays_MWArray_ToArray.htm

Products


Release

R2023a

Community Treasure Hunt

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

Start Hunting!