%% Integrate External Code that Uses Pointers, Structures, and Arrays
% This example shows how to integrate external code that operates on a C 
% style array with MATLAB(R) code. The external code computes a summation over array data.
% You can customize the code to change the input data or computation.
%
% This example shows how to combine multiple 
% different elements of external code integration functionality. For example, you:
%
% * Interface with an external structure type by using |coder.cstructname|
% * Interface with an external pointer type by using |coder.opaque|
% * Execute external code by using |coder.ceval|
% * Pass data by reference to external code by using |coder.ref|
%
% Copyright 2018 The MathWorks, Inc.

%% Explore the Integrated Code
% The extSum function uses external C code to compute a summation operation
% on an array of 32-bit integers. The array size is controlled by a user
% input. 
%
% <include>extSum</include>
%
% To simplify the generated code, you set bounds on the
% size of the array. The bounds prevents the use of dynamic memory
% allocation in the generated code.
%
% The function |makeStruct| declares a
% MATLAB structure type and initializes one of the fields to a pointer type
% by using |coder.opaque|. The C structure corresponding to this definition
% is contained in a header file that you provide by using the |HeaderFile|
% parameter in the |coder.cstructname| function. The C structure type
% provides a simple representation for an array of integers.
%
% <include>makeStruct</include>
%
% With the external structure type fully initialized, you pass
% it as an input to the external code in the |callExtCode| function. This
% function initializes the array, calls an operation on the array to return
% a single output, and then frees the initialized memory. 
%
% <include>callExtCode</include>
%
% The function uses |coder.updateBuildInfo| to provide the .c file to the
% code generator.

%% Generate a MEX Function 
% To generate a MEX function that you can run and
% test in MATLAB, enter: 

codegen extSum -args {10} 

%%
% Test the MEX function. Enter: 

extSum_mex(10) 

%%
% The external C code, contained in the files
% |arrayCode.c| and |arrayCode.h|, uses the custom type definition |int32_T|. The
% generated MEX code produces and uses this custom type definition. If you
% want to generate standalone (lib, dll, or exe) code that uses this custom
% data type, then you can modify the |DataTypeReplacement| property of your
% configuration object. See <docid:coder_ug#mw_ffc30033-4ec1-42a2-aa5b-cc5ee80eeb73
% Mapping MATLAB Types to Types in Generated Code>.