How can I use a DLL file in Simulink?
96 views (last 30 days)
Show older comments
MathWorks Support Team
on 15 Feb 2013
Edited: MathWorks Support Team
on 2 Aug 2024
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
on 2 Aug 2024
Edited: MathWorks Support Team
on 2 Aug 2024
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:
As outlined in depth in the paper above (specifically in "html/simulink_shrlib.html"), you can load a DLL in Simulink using C Caller Blocks, C Function Blocks, and C MEX S-Function Blocks, among other ways.
The following description explains how to use S-Functions to load and incorporate a DLL:
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.
To learn more about S-Functions, run the following commands in MATLAB Command Window to find the documentation specific to your release:
>> doc S-Function
>> doc C MEX S-Function Examples
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"
LoadLibrary()
GetProcAddress()
FreeLibrary()
For Linux, one can use:
#include "dlfcn.h"
dlopen()
dlsym()
dlclose()
The link below has a tutorial on how to load a DLL in C:
Note: Using DLLs currently requires header files to be able to call shared library functions. Following is the link to documentation that mentions this limitation:
0 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!