User`s guide

5 Controlling Code Generation
5-40
Interfacing M-Code to C/C++ Code
The MATLAB Compiler 2.1 supports c alling arbitrary C/C++ functions from
your M-code. You simply provide a n M-function stub that determines how the
code will behave in M, and then provide an implementation of the body of the
function in C or C++.
C Example
Suppose you have a C function that reads data from a measurement device. In
M-code, you want to simulate the device by providing a sine wave output. In
production, you want to provide a function that returns the measurement
obtained from the device. You have a C function c alled
measure_from_device() that returns a double, which is the current
measurement.
collect.m contains the M-code for the simulation of your application.
function collect
y = zeros(1, 100); %Pre-allocate the matrix
for i = 1:100
y(i) = collect_one;
end
function y = collect_one
persistent t;
if (isempty(t))
t = 0;
end
t = t + 0.05;
y = sin(t);
The next step is to replace the implementation of the collect_one function
with a C implementation that provides the correct value from the device each
time it is requested. This is accomplished by using the
%#external pragma.
The
%#external pragma informs the MATLAB Compiler that the
implementation version of the function (
Mf) will be hand written and will not
be generated from the M-code. This pragma affects only the single function in
which it appears. Any M-function may contain this pragma (local, global,