Pass Structures

Add Values of Fields in Structure

This example shows how to pass a MATLAB® structure to the function, addStructFields. addStructFields, in the shrlibsample.c example library, sums the values of the fields in a structure.

Read the function signature.

 addStructFields Function Signature

The input argument is a structure of type c_struct.

Look at the definition in the shrlibsample.h header file for information about how to create the structure.

 c_struct Structure Definition

Create and initialize structure sm:

sm.p1 = 476;
sm.p2 = -299;
sm.p3 = 1000;

Each field is of type double.

Load the library.

if not(libisloaded('shrlibsample'))
  addpath(fullfile(matlabroot,'extern','examples','shrlib'))
  loadlibrary('shrlibsample')
end

Call the function.

calllib('shrlibsample','addStructFields',sm)
ans =
        1177

MATLAB automatically converts the fields of structure sm to the library definition for c_struct.

Preconvert MATLAB Structure Before Adding Values

This example shows how to preconvert structure sm to c_struct before calling addStructFields.

Create and initialize structure sm:

sm.p1 = 476;
sm.p2 = -299;
sm.p3 = 1000;

Convert the fields, which are of type double, to match the c_struct structure type.

if (libisloaded('shrlibsample'))
  sc = libstruct('c_struct',sm);
end

The fields of libstruct object sc are double, short, and long.

Call the function.

calllib('shrlibsample','addStructFields',sc)
ans =
        1177

Display Structure Field Names

This example shows how to display the field names of an externally-defined structure.

Create a libstruct object from c_struct, in the shrlibsample.c example library.

if (libisloaded('shrlibsample'))
  s = libstruct('c_struct');
end

To get the names of the fields, type:

get(s)
    p1: 0 
    p2: 0 
    p3: 0

MATLAB displays the field names p1, p2, and p3 and their values.

See Also

More About

Was this topic helpful?