MATLAB: How to call a DLL created from Simulink model in a Visual Studio application

Embedded Codersimulink coder

The documentation section on "Host-Based Shared Library Limitations" under Real-Time Workshop Embedded Coder :
<http://www.mathworks.com/help/releases/R2015b/ecoder/ug/creating-and-using-host-based-shared-libraries.html#bq2nufb-1>
mentions:
On Windows systems, the ert_shrlib target by default does not generate or retain the .lib file for implicit linking (explicit linking is preferred for portability).
You can change the default behavior and retain the .lib file by modifying the corresponding template makefile (TMF). If you do this, be aware that the generated model.h file will need a small modification to be used together with the generated ert_main.c for implicit linking. For example, if you are using the Microsoft Visual C++ development system, you will need to declare __declspec(dllimport) in front of all data to be imported implicitly from the shared library file.
I would like to know which TMF file needs to be modified, and how I modify the model header files.

Best Answer

The TMF file that the documentation refers is the TMF file for the compiler that you have set. Suppose you are using Visual C compiler, you can find the actual tmf file under the following directory:
~matlabroot/rtw/c/ert/ert_vc.tmf
Where 'matlabroot' is the installation directory of your version of MATLAB.
In this file, search for the following section:
#--- Comment out the next line to retain .lib and .exp files ---
@del $(RELATIVE_PATH_TO_ANCHOR)\$(MODEL)_win32.lib
$(RELATIVE_PATH_TO_ANCHOR)\$(MODEL)_win32.exp
As indicated above, if you comment out this section it should retain the '.lib' file.
For the point about modifying the header files:
There are two ways using DLLs:
1. Explicit : This way of using DLLs is demonstrated in the demo named 'rtwdemo_shrlib.mdl' and related examples. This way of linking is more portable (DLL are compiler independent, LIB are compiler dependent)
2. Implicit : Keep the import library LIB file and link against this LIB file. For MS VC, it is required to have every Symbol that would be in such imported library to be decorated with __declspec(dllimport) so that the user's application(caller of the functions in dll) , which should #include a header file that describes the DLL modules/data, can find the correct symbol in the DLL. The aforementioned header file can be derived from our generated model.h but must be modified as document stated.
A simple example:
In the model.h
extern void nestedop_step(void);
shall be changed as in the modified header
__declspec(dllimport) void nestedop_step(void);
This usage is more on the caller of the DLL side thus we would recommend the user to check examples on Microsoft website about how to call a function in DLL.
<http://msdn.microsoft.com/en-us/library/3y1sfaz2(VS.80).aspx>