I have spent a significant amount of time attempting to write a dll in C/C++ and call it in Matlab. An article was previously written on this topic at http://guoliangye.com/2009/01/21/how-to-write-a-dll-in-cc-and-call-it-in-matlab/ (link no longer working as of 2018) but I feel the need to discuss it further in both the Windows and Linux environments.
In Windows 32 bit with 32 bit MATLAB.
1) Create two files named Test.h and Test.cpp
Test.h
#ifndef MY_API
#define MY_API extern “C” __declspec(dllexport)
#endif
MY_API int add(int a, int b);
MY_API int sub(int a, int b);
Test.cpp
#ifndef MY_API
#define MY_API extern “C” __declspec(dllexport)
#endif
#include “Test.h”
int add(int a,int b)
{
return a + b;
}
int sub(int a,int b)
{
return a – b;
}
2) Compile into a DLL (.dll) file using Visual Studio 2008 Professional or Express Edition. If neither is installed, you will need to download and install. Check the MATLAB documentation to see the list of all of the supported compilers for your version of MATLAB .
Step by step instructions for creating a .dll using Visual Studio can be found at http://msdn.microsoft.com/en-us/library/ms235636(VS.80).aspx
3) You then need to copy the newly created .dll file along with the original .h file to a MATLAB directory search path or you can just include the call to the directory.
Now open MATLAB and type
loadlibrary(‘Test.dll’, ‘Test.h’);
4) You can view the newly loaded function using
libfunctionsview Test;
5) You can also call the functions such as
A = calllib(‘Test’,’add’,5,4);
B = calllib(‘Test’,’sub’,5,4);
6) You can also unload the library using
unloadlibrary Test
In Windows 64 bit with 64 bit MATLAB.
Getting the dll file to compile in the 64 bit Windows version is a bit more tricky. MATLAB wants a C file not a C++ file. So one needs to be careful.
1) Create two files named Test.h and Test.c
Test.h
int sum(int, int);
Test.c
__declspec(dllexport) int sum(int a, int b)
{
return a + b;
}
NOTE: A “.c” file is not a selectable file type in Visual Studio 2008 so you may have to manually enter the file extension. You can select a .cpp file when adding to your project, but make sure to call it ‘Test.c’ so that .cpp is not the extension.
2) Compile into a DLL (.dll) file using Visual Studio 2008 Professional SP1. Check the MATLAB documentation to see the list of all of the supported compilers for your version of MATLAB .
Step by step instructions for creating a .dll using Visual Studio can be found at http://msdn.microsoft.com/en-us/library/ms235636(VS.80).aspx
However, you need to be careful here. Before building the dll you need to go into properities and then the configuration manager and then choose a new active solution platform. Then you need to select ‘x64’ copy the settings for win32 and click OK.
Now you may or may not see x64. By default the x64 compiler is not installed during the install of Microsoft Visual Studio 2008 Pro. You will need to select it or just choose the full install. Even doing this I had an issue where it would not show up unless I also installed SP1. So make sure you install SP1 and select the x64 compilers if you do not do a full install, they are not default.
These instructions go into more details on getting a x64 .dll to work http://msdn.microsoft.com/en-us/library/9yb4317s.aspx.
3) You then need to copy the newly created .dll file along with the original .h file to a MATLAB directory search path or you can just include the call to the directory.
Now open MATLAB and type
loadlibrary(‘Test.dll’, ‘Test.h’);
4) You can view the newly loaded function using
libfunctionsview Test;
5) You can also call the functions such as
C = calllib(‘Test’,’sum’,5,4);
6) You can also unload the library using
unloadlibrary Test
In Linux 64 bit with 64 bit MATLAB.
1) Create two files named Test.h and Test.c
Test.h
int add(int a, int b);
int sub(int a, int b);
Test.c
#include “Test.h”
int add(int a,int b)
{
return a + b;
}
int sub(int a,int b)
{
return a – b;
}
NOTE: An extra return should be added to the end of both of these files.
2) You will want to open up the Terminal. Then you will want to enter
sudo apt-get install build-essential
This will install gcc/gcc++ which will be needed to compile.
You will be compiling into a .so file. To do this make sure the two files you created in (1) are located in your username directory, if not copy them there. Then in the terminal type the following
gcc -c -fPIC Test.c -o Test.o
gcc -shared -Wl,-soname,Test.so.1 -o Test.so Test.o
3) You then need to copy the newly created .so file along with the original .h file to a MATLAB directory search path or you can just include the call to the directory.
Now open MATLAB and type
loadlibrary(‘/home/username/Test’,’/home/username/Test.h’)
Where username is the username you are on your Linux Install.
4) You can view the newly loaded function using
libfunctionsview Test;
5) You can also call the functions such as
A = calllib(‘Test’,’add’,5,4);
B = calllib(‘Test’,’sub’,5,4);
6) You can also unload the library using
unloadlibrary Test
NOTE:
The above was originally run and tested in December 2009 on a computer running Windows XP 32 bit and MATLAB 2009 B 32 bit version, on a computer running Windows 7 64 bit and MATLAB 2009 B 64 bit, and on a computer running Ubuntu 9.04 64 bit computer running MATLAB 2009 A 64 bit version.
This was also tested in November 2010 as an update on a computer running Ubuntu 10.10 64 bit with MATLAB 2010 B 64 bit version.
Refer to the latest MATLAB documentation for updates and what compiler you will need.
MATLAB documentation provides further information of using C shared libraries in MATLAB.
Further you may encounter errors relating to copying and pasting the above directly into files. Therefore I encourage you to directly type out all the files and commands.
Permalink
Thanks for this usefull blog entry!
Permalink
Thank you very much for your sharing.
I also installed Microsoft Visual Studio 2008 Pro SP1 and MATLAB 2009b on my computer. But When I tried to use ‘loadlibrary’, it always came out an error that ‘fatal error C1083: Cannot open include file:’test.h’: No such file or directory’
Do you have any idea where the problem is?
Any help would be appreciated.
Xin
Permalink
Hi Xin
Do you make sure you have the test.h and test.dll files in the current MATLAB directory. When you open MATLAB you need to make sure you browse to the correct folder so that you can see the files on the left sidebar in MATLAB default view.
If you are using 64 bit Windows did you make sure you did a full install and/or installed the 64 bit compilers.
Did you make sure you compiled both the header and source files correctly into the dll? MATLAB needs the header file and the dll file.
Permalink
Hi Todd,
Thank you very much for your reply.
I am sure that I chose full install during the install of visual studio. But I got the following in MATLAB:
>> !set VS
VS90COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools\
>> !”%VS90COMNTOOLS%..\..\VC\vcvarsall.bat”
Setting environment for using Microsoft Visual Studio 2008 x86 tools.
I think MATLAB is using the x86 compiler instead of x64. Do you know how to check the x64 compiler? I have re-installed the visual studio several times, and it still goes like this.
Thanks a lot for your help.
Xin
Permalink
Hi Xin,
There are very specific steps to take when doing this which I have outlined in my blog post. I have successfully set this up numerous times with different versions of MATLAB and on different machines.
I encourage you to carefully review my post and perform the steps. Then explain to me specifically what the problem is if you are still having difficulty. You may need to install Windows SDK. I also recommend seeking advice on mathworks.com in the forums as people who develop MATLAB regularly post and check there.
Permalink
Hi
I downloaded Microsoft SDK with the “x64 Compilers and Tools”. I have VS2008 Professional from before. When I follow the example on this page, for the case “Windows 64 bit with 64 bit MATLAB”, I get the following error:
??? Error using ==> loadlibrary at 368
Failed to preprocess the input file.
Output from preprocessor is:’cl’ is not recognized as an internal or external command, operable program or batch file.
The error comes when loadlibrary is trying to evaluate: [res,ccout]=system(preprocess_command),
where
preprocess_command =
“%VS90COMNTOOLS%..\..\VC\vcvarsall.bat” amd64>nul&cl -nologo -I”C:\Program Files\Matlab\extern\include” -E “C:\Users\myUser\Desktop\Loadlibrary test\Test.h” > “Test.i”
If I remove the call to system(); I get the following error message later in the code:
??? Error using ==> loadlibrary at 388
Call to Perl failed. Possible error processing header file.
Output of Perl command:
Can not open file Test.i because No such file or directory at C:\Program
Files\Matlab\toolbox\matlab\general\private\prototypes.pl line 34.
Can you help me please? What should I do?
/Tobias
Permalink
Hi Tobias,
I have seen that error before. You need to be very careful that you have followed all of the steps outlined above such as having Visual Studio 2008 Pro SP1 installed with the 64 bit compilers.
That error may be occurring because it is attempting to use a 32 bit compiler, but I can’t remember entirely.
I encourage you to visit the mathworks.com forums and read up on MATLAB documentation if you are still having difficulty.
Permalink
Oh Yes. 6 houre searching an dnow i have the answer. you are my new hero for today!
thanks soooooo much!
greetings
Permalink
Hi,
I tried the Win64/Matlab64 example but when building the DLL I received the error: C1853: ‘x64\Release\test.pch’ precompiled header is from a previous version of the compiler, or the precompiled header is C++ and you are using it from C (or vice cersa)
I tried renaming test.cpp and it will build and loadlibrary in Matlab but not calllib, any ideas? thank you
Permalink
hmm not sure Nick, it worked as tested for the configurations indicated above. What version of Visual Studio are you using?
Permalink
Great Tutorial! Thanks a lot!
One small thing: before running loadlibrary(…), one should make sure the right compiler is selected: mex -setup