MATLAB Compiler Previous page   Next Page

C++ Shared Library Example

This example rewrites the previous C shared library example using C++. The procedure for creating a C++ shared library from M-files is identical to the procedure for creating a C shared library, except you use the cpplib wrapper.

The -W cpplib:<libname> option tells the MATLAB Compiler to generate a function wrapper for a shared library and call it <libname>. The -T link:lib option specifies the target output as a shared library. Note the directory where the Compiler puts the shared library because you will need it later on.

Writing the Driver Application

This example uses a C++ version of the matrixdriver application, matrixdriver.cpp.

Compiling the Driver Application

To compile the matrixdriver.cpp driver code, you use your C++ compiler. By executing the following mbuild command that corresponds to you development platform, you will use your C++ compiler to compile the code.

Incorporating a C++ Shared Library Into an Application

To incorporate a C++ shared library into your application, you will, in general, follow the steps listed in Steps to Use a Shared Library. There are two main differences to note when using a C++ shared library.

Exported Function Signature

The C++ shared library target generates two sets of interfaces for each M-function. The first set of exported interfaces is identical to the mlx signatures that are generated in C shared libraries. The second set of interfaces is the C++ function interfaces. The generic signature of the exported C++ functions is

M-functions with no return values.   

M-functions with at least one return value.   

In this case, <list_of_input_variables> represents a comma-separated list of type const mwArray& and <list_of_return_variables> represents a comma-separated list of type mwArray&. For example, in the libmatrix library, the C++ interfaces to the addmatrix M-function is generated as

Error Handling

C++ interface functions handle errors during execution by throwing a C++ exception. Use the mwException class for this purpose. Your application can catch mwExceptions and query the what() method to get the error message. To correctly handle errors when calling the C++ interface functions, wrap each call inside a try-catch block.

The matrixdriver.cpp application illustrates the typical way to handle errors when calling the C++ interface functions.


Previous page  C++ Shared Library Target MATLAB Compiler-Generated Interface Functions Next page

© 1994-2005 The MathWorks, Inc.