MATLAB: How to use multi-level structures for passing it into a C++ shared library

MATLAB Compilermulti-levelmwarraynested

I am using the MATLAB Compiler to generate C++ shared libraries. I need to use the mwArray data type in order to pass multi-level structures between my C++ driver function and the shared library. I would like an example which illustrates how this can be done.

Best Answer

The following example creates a C++ shared library and then calls it from a C++ driver function. A function in the library takes a multi-level structure as an input and prints the contents of each field of each index.
1. Execute:
mbuild –setup
from the MATLAB command prompt and select your C++ compiler.
2. Copy the following code to a new MATLAB source file named “dispstruct.m” in your build directory:
function dispstruct(x)
disp('Field names of struct array are:');
fnames = fieldnames(x);
for k = 1:size(x,2)
disp(['Contents of struct array at index: ' num2str(k)]);
disp([fnames{1} ': ' getfield(x,{1,k},fnames{1})]);
disp([fnames{2} ': ' num2str(getfield(x,{1,k},fnames{2}))]);
substruct = getfield(x,{1,k},fnames{3});
subfnames = fieldnames(substruct);
disp(['The contents of sub structure: ' fnames{3}]);
for j = 1:size(substruct,1)
disp([subfnames{1} ': ' getfield(substruct,{1,j},subfnames{1})]);
disp([subfnames{2} ': ' getfield(substruct,{1,j},subfnames{2})]);
end
end
3. To create the C++ shared library, execute the following command at the MATLAB Command line:
mcc -W cpplib:structlib -T link:lib dispstruct.m
4. Download the attached MWStructExample.cpp file.
5. Compile the MWStructExample.cpp function with:
mbuild MWStructExample.cpp structlib.lib
6. You will now have a file MWStructExample.exe, which, when run, should display the contents of a structure array created in the C++ code. The output looks like:
Field names of struct array are:
Contents of struct array at index: 1
name: Jordan Robert
phone: 3386
The contents of sub structure: hometown
city: Bern
country: CH
Contents of struct array at index: 2
name: Mary Smith
phone: 3912
The contents of sub structure: hometown
city: London
country: UK
Contents of struct array at index: 3
name: Stacy Flora
phone: 3238
The contents of sub structure: hometown
city: Nairobi
country: KE
Contents of struct array at index: 4
name: Harry Alpert
phone: 3077
The contents of sub structure: hometown
city: Washington
country: US
Related Question