Call C++ Class Methods Using a C-style Wrapper Function from a C Function Block
This example shows how to use the C Function block to call C++ class methods using a C-style wrapper function. For some C++ classes, such as template classes, the C Function block does not support direct instantiation of class objects or calling of class methods, so it is necessary to use C wrapper functions. See Interface with C++ Classes Using C Function Block. For an example of a C Function block accessing C++ class members and methods directly, see Call C++ Class Methods Directly from a C Function Block.
In this example, the C-style wrapper functions are declared in
adder_wrapper.h and implemented in
To run this example model, you must configure MATLAB® to use a C++ compiler. This can be done using the
mex -setup command, and selecting a C++ compiler.
To enable calling of the C functions from the C Function block, in the model, specify the header file and the source file in the Simulation Target pane of the Model Configuration Parameters dialog. In this model the custom code header file
adder_template.h defines an
adder class template along with the class member functions. The header file
adder_wrapper.h contains declarations of C-style wrapper functions which are called in the C Function block. The prototypes of the C-style wrapper functions are:
void deleteAdder(void *obj)
int adderOutput(void *obj, int increment)
void *obj is the class object handle and
increment is an input used by the adder function.
createAdder function is called in the Start Code section of the C Function block dialog to construct an object of the
adder class. The
deleteAdder function is called in the Terminate Code section to destruct the
adder class object. In the Output Code section, the
adderOutput function is called. In this example the ports of the C Function block are configured as follows:
obj, return by the
createAdderfunction, is a
Persistentsymbol of the C Function block.
The input of the C Function block is mapped to
The output of the C Function block is mapped to the return value of the