How can I use a DLL file in Simulink?

305 views (last 30 days)
I have a dynamic-link library (DLL) for Windows. How can I load the DLL and use its functions in Simulink?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 26 Mar 2023
Edited: MathWorks Support Team on 27 Mar 2023
There are several ways to do this. For a list of ways to incorporate the DLL, please refer to the paper available at the following link: 
One way to load a DLL in Simulink is to use the
C MEX S-function
block; its documentation page is linked below for reference:
To find the documentation specific to your release, type the following command in MATLAB command window:
>> doc S-Function
You can look up how to write S-Functions using the documentation. To get started, you can have a look that following S-function examples:
To find the documentation specific to your release, type the following command in MATLAB command window:
>> doc C MEX S-Function Examples
In the attached zip files, you can find two example C MEX S Functions that load a DLL on Windows OS. The DLL from 2013 is set up in a 32-bit Visual Studio project. You need to 32-bit MATLAB to load this DLL as configured or change the Visual Studio configuration to be 64-bit. The DLL from 2020 is 64-bit and uses an S-Function Builder block to simplify the setup.
Essentially, in the S Function C code, you need to create a Pointer Work Vector that will store the addresses of the library functions. Key points to note:
1) Include "windows.h" in order to use LoadLibrary, GetProcAddress and FreeLibrary from this file.
2) Use "ssSetNumPWork" to set up the Pointer Work Vector in mdlInitializeSizes function.
3) Use "LoadLibrary" in the mdlStart function to load the DLL file to memory.
4) Use "ssSetPWorkValue" to set the Pointer Work Vector elements to point to the DLL file and its functions of interest. This can be done in mdlStart function as well.
5) Make sure use "FreeLibrary" in the mdlTerminate function to unload the library from the memory.
For Windows, one can use:
#include "windows.h"
For Linux, one can use:
#include "dlfcn.h"
Lastly, the link below has a tutorial on how to load a DLL in C:

More Answers (0)


Find more on Simulink Environment Customization in Help Center and File Exchange




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by