How can I call a DLL or Shared Library function using MEX-files instead of the Generic DLL / Shared Library Interface?

38 views (last 30 days)
I cannot use the LOADLIBRARY function, either because CALLLIB does not support some feature of my library, or because LOADLIBRARY is not supported on my platform. I would therefore like to call a library function using a MEX-file.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
This change has been incorporated into the documentation in Release 2009a (R2009a). For previous releases, read below for any additional information:
This is a basic example of calling one of the C Structure examples from the Generic DLL documentation using the MEX interface. Much of the work is doing the data conversion that is normally handled by the CALLLIB, LIBPOINTER, and LIBSTRUCT functions.
This example is configured for 32-bit MATLAB 7.4 (R2007a) and Microsoft Visual Studio 2005. Code will be similar but compiler options files will be different for other configurations. For example, the BAT-file will be a SH-file on Linux. The attached BAT-file is a modified version of the MSVC80OPTS.BAT file which is shipped with MATLAB in the following directory:
<matlabroot>/bin/win32/mexopts
A similar file is available on other platforms in the following directory:
<matlabroot>/bin
The C-code is platform independent, but it is compiled into a library which has different extensions depending on the platform, so the two MEX commands below will need to be modified based on the platform.
To execute this example, please download the attached C- and BAT-files to a working directory, and execute:
copyfile([matlabroot '\extern\examples\shrlib\shrlibsample.c']);
copyfile([matlabroot '\extern\examples\shrlib\shrlibsample.h']);
copyfile([matlabroot '\extern\examples\shrlib\shrhelp.h']);
mex -v -g -f msvc80buildlib.bat shrlibsample.c
mex -v -g myAddStructByRef.c shrlibsample.lib
struct.p1 = 4; struct.p2 = 7.3; struct.p3 = -290;
[res,st] = myAddStructByRef(struct)
This copies the Generic DLL example files to your working directory, builds the DLL with all relevant Exports files and import libraries (EXP- and LIB-files), then builds the MEX-file to call addStructByRef(). Finally, it calls the function on a test structure.
This will produce output similar to:
C Struct:
p1: 4.000000
p2: 7
p3: -290
Calculated sum: -279.000000
res =
p1: 5.5000
p2: 1234
p3: 12345678
st =
-279
This calls the same function used in the CALLLIB documentation:
addpath([matlabroot '\extern\examples\shrlib'])
loadlibrary shrlibsample shrlibsample.h
struct.p1 = 4; struct.p2 = 7.3; struct.p3 = -290;
[res,st] = calllib('shrlibsample','addStructByRef',...
libstruct('c_struct',struct));

More Answers (0)

Products


Release

R2007a

Community Treasure Hunt

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

Start Hunting!