Wednesday, August 19, 2009

Interfacing Matlab and C/C++ using direct dll invocation

Suppose I have an algorithm the implementation of which if run from Matlab is going to take forever. Fortunately I got an implementation of this in c/c++ and would like to invoke this c++ code from Matlab. There are quite a few conventional ways of doing this.
1) invoking the c++ exe file from Matlab passing the right arguments. This is not very attractive since the exe has to be loaded everytime it is going to be used and I am planning to use it atleast a million times in experiment.

2) writing a mex function wrapper for over the c++ implementation and then call the function from matlab. I went quite far with this approach, but the farther I went, it looked lesser appealing due to the following points:
a) there are only a few compilers supported by matlab for building c/c++ files (using the mcc setup). I am using matlab 2006, and it has only lcc and microsoft visual studio without .net supported. I installed another Borland c++ lightweight compiler for the purpose, but the c++ syntax rules were a bit different in it from vc++ syntax and more over I had to convert my other library inclusions to borland omp format using coff2omp.exe utility. Overall it was a pain.
b) I needed to learn a lot of matlab memory allocation and deallocation apis to use the mex files. And I wanted a very fast way of coding this up.
c) The VC++ IDE was useless other than just for coding up my c++ code. It would be nicer if I could use the vc++ ide for building and debugging the code.

3) The above problems motivated me to look at the following very elegant solution, which is to build the c++ algorithm into a dll file and load the dll inside matlab, later calling the function directly.

Here are the steps to do this:
1) Write up your code in VC++ and build it to a dll.  (In case of Linux, you need to build the code to a shared library object using g++ -shared option).
a) You need to change the "configuration type" in the project properties to dll for this.
b) Also, you need to add a __declspec (dllexport) to the function you would like export to matlab. For ex:

__declspec (dllexport) double* MyMatlabFunction(char*, int*, int );

Place all such exports in a single header file, say functionexports.h (this will be required later).
c) Build the code and create a dll, (say mycode.dll) using vc++.

2) load the dll in matlab.
a) loadlibrary(), function in matlab loads a dll. the syntax is given below:
>loadlibrary('mycode', 'functionexports.h');
Note that you need to pass in the dll name and the headerfile referred above to the loadlibrary call. You can check if the library is already loaded using the "libisloaded('mycode.dll')" call and use unloadlibrary('mycode.dll'); to unload a library (which might be needed if you want to rebuild your dll from vc++).

b) Once the dll is loaded, use the calllib() function to invoke the exported dll function. The syntax is as follows:
[outargs]=calllib('libname', 'funname', inargs);
ex: [dptr]= calllib('mycode', 'MyMatlabFunction', 'somestring', x, y);
Thats it.

c) a little tricky part here is to operate on the arguments to and from the function. A good tutorial on how to do this is given in the link here .

A simple example that calls a c++ function that takes three arguments; a string, an integer pointer and an integer, and returning a double pointer is given below:
Matlab call Example:
function [sift, n]=ComputeSift(imgfilename, disp)
tic;
if ~libisloaded('siftlight')
loadlibrary('siftlight', 'siftlight.h');
end

sift=0; n=0;
nptr=libpointer('int32Ptr', n);
siftptr=calllib('siftlight', 'mysift', imgfilename, fptr, disp);

if fptr.Value > 0
setdatatype(siftptr, 'doublePtr', 128, fptr.Value);
sift=siftptr.Value;
n=fptr.Value;
end

t=toc;
fprintf('sift took %f seconds...\n', t);
end

The solution is fast and elegant, you can use the whole power of VC++ for building and debugging, and there is very less to learn (you should just know how to pass in and take back arguments from the call). Hope this information is helpful.

50 comments:

Anonymous said...

I want not acquiesce in on it. I think polite post. Specially the appellation attracted me to be familiar with the intact story.

Anonymous said...

Amiable dispatch and this mail helped me alot in my college assignement. Thank you for your information.

Anonymous said...

Well I acquiesce in but I contemplate the post should secure more info then it has.

Hassan said...

Your post helped me a lot.
thanks.

Anonymous said...

Genial post and this enter helped me alot in my college assignement. Say thank you you seeking your information.

Anonymous said...

[... ] is another useful source of tips on this issue[...]
http://cellphone-gps.info/

Anonymous said...

interesting post. I would love to follow you on twitter.

Anonymous said...

Infatuation casinos? recognize this advanced [url=http://www.realcazinoz.com]casino[/url] president and fit in secure of up online casino games like slots, blackjack, roulette, baccarat and more at www.realcazinoz.com .
you can also balk our late [url=http://freecasinogames2010.webs.com]casino[/url] orientate at http://freecasinogames2010.webs.com and debate postponed accurate dab !
another boaster [url=http://www.ttittancasino.com]casino spiele[/url] principled is www.ttittancasino.com , because german gamblers, boo-boo in unrestrained online casino bonus.

Anonymous said...

cause in track down this explicit of impairment [url=http://www.casinoapart.com]casino[/url] hand-out at the prime [url=http://www.casinoapart.com]online casino[/url] guide with 10's of spiffy [url=http://www.casinoapart.com]online casinos[/url]. actions [url=http://www.casinoapart.com/articles/play-roulette.html]roulette[/url], [url=http://www.casinoapart.com/articles/play-slots.html]slots[/url] and [url=http://www.casinoapart.com/articles/play-baccarat.html]baccarat[/url] at this [url=http://www.casinoapart.com/articles/no-deposit-casinos.html]no plunk casino[/url] , www.casinoapart.com
the finest [url=http://de.casinoapart.com]casino[/url] against UK, german and all to the world. so on the side of the choicest [url=http://es.casinoapart.com]casino en linea[/url] confirmation us now.

Anonymous said...

Good dispatch and this enter helped me alot in my college assignement. Thanks you seeking your information.

Anonymous said...

It isn't hard at all to start making money online in the underground world of [URL=http://www.www.blackhatmoneymaker.com]clickbank blackhat[/URL], You are far from alone if you don't know what blackhat is. Blackhat marketing uses little-known or little-understood methods to build an income online.

Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...

top [url=http://www.c-online-casino.co.uk/]free casino bonus[/url] coincide the latest [url=http://www.casinolasvegass.com/]casino[/url] free no set aside reward at the foremost [url=http://www.baywatchcasino.com/]online casinos
[/url].

Anonymous said...

It's awesome to visit this web site and reading the views of all friends about this piece of writing, while I am also zealous of getting familiarity.

My web site online casino

Anonymous said...

Good article! We are linking to this particularly great post on our site.
Keep up the good writing.

Feel free to visit my weblog - electronic cigarette company

Anonymous said...

hallo anoop,

thanks for the detailed explanation.

i have a question - i have a visual studio solution in c++ including opencv and others that i want to use under matlab. is the method of loading dll's applicable in my case? i understood from the mathworks site that they only support c, that means no methods in classes and structs.

i would appreciate any help.

thanks

dan

Anonymous said...

electronic cigarette, e cigarette forum, buy electronic cigarette, e cigarette health, electronic cigarette, smokeless cigarettes

Karthika Shree said...

Finding the time and actual effort to create a superb article like this is great thing. I’ll learn many new stuff right here! Good luck for the next post buddy..
Matlab Training in Chennai

Anonymous said...

thank the good topic.
Welcome To Casino online Please Click the website
thank you.
gclub online
goldenslot
gclub online

Mounika said...

It seems you are so busy in last month. The detail you shared about your work and it is really impressive that's why i am waiting for your post because i get the new ideas over here and you really write so well.
Click here:
python training in tambaram
Click here:
python training in annanagar

pooja said...

A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you.

Blueprism training in Chennai

Blueprism training in Bangalore

Blueprism training in Pune

shethal said...

This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 
Devops Training in Chennai
Devops Training in Bangalore

nilashri said...

I simply wanted to write down a quick word to say thanks to you for those wonderful tips and hints you are showing on this site.
Data Science training in Chennai | Data science training in bangalore
Data science training in pune | Data science online training
Data Science Interview questions and answers

Unknown said...

Excellant post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
java training in tambaram | java training in velachery

java training in omr | oracle training in chennai

Anonymous said...

Thank you for allowing me to read it, welcome to the next in a recent article. And thanks for sharing the nice article, keep posting or updating news article.
angularjs Training in electronic-city

angularjs online Training

angularjs Training in marathahalli

angularjs interview questions and answers

angularjs Training in bangalore

angularjs Training in bangalore

Anonymous said...

Nice blog..! I really loved reading through this article. Thanks for sharing such an amazing post with us and keep blogging...Well written article Thank You for Sharing with Us pmp training institute in chennai | pmp training class in chennai | pmp training near me | pmp training courses online | pmp training fee

Suba said...

Blog with more latest info stuffed. Thanks for sharing with us.

Selenium Training in Chennai
Selenium Training
iOS Training in Chennai
French Classes in Chennai
Big Data Training in Chennai
web designing course in chennai
web designing training in chennai
web design training chennai

Sadhana Rathore said...

Thanks for sharing this information admin, it helps me to learn new things. Waiting for more updates.
Python Training in T.Nagar
Python and Django Training in Chennai
Data Science Course in Chennai
Data Science Training in Chennai
AWS Certification in Chennai
Angularjs course in Chennai
RPA course in Chennai

sathish said...

This is quite educational arrange. It has famous breeding about what I rarity to vouch. Colossal proverb. This trumpet is a famous tone to nab to troths. Congratulations on a career well achieved. This arrange is synchronous s informative impolites festivity to pity. I appreciated what you ok extremely here 
angularjs online training

apache spark online training

informatica mdm online training

devops online training

aws online training

dhanam said...

Excellent blog, I wish to share your post with my folks circle. It’s really helped me a lot, so keep sharing post like this
Microsoft Azure online training
Selenium online training
Java online training
Python online training
uipath online training

Aaditya said...

Thank you for your post, it is very useful for c and c++ users.

Data Science Courses Bangalore

zaintech99 said...

I finally found great post here.I will get back here. I just added your blog to my bookmark sites. thanks.Quality posts is the crucial to invite the visitors to visit the web page, that's what this web page is providing.
date analytics certification training courses
data science courses training

data science analytics rakshi said...

Really appreciate this wonderful post that you have provided for us.Great site and a great topic as well i really get amazed to read this. Its really good.data science course in dubai

zaintech99 said...

Its as if you had a great grasp on the subject matter, but you forgot to include your readers. Perhaps you should think about this from more than one angle.
www.technewworld.in
How to Start A blog 2019
Eid AL ADHA

lucy88 said...

This is also a very good post which I really enjoyed reading. It is not every day that I have the possibility to see something like this,
Great website

Anonymous said...

I am impressed by the information that you have on this blog. It shows how well you understand this subject .

Free Online Betting said...

Awesome blog, i always enjoy & read the post you are sharing!
Thank for your very good article...!
ทาง เข้า sbo มือ ถือ ล่าสุด
คาสิโนออนไลน์
บาคาร่าออนไลน์
สล็อตออนไลน์


gclubpok9
gclubonline168
slotscr168
aset4bet

nisha said...

Excellent post. the post is really very Impressive. every content should be very neatly Represented.

Data Science Training Course In Chennai | Data Science Training Course In Anna Nagar | Data Science Training Course In OMR | Data Science Training Course In Porur | Data Science Training Course In Tambaram | Data Science Training Course In Velachery

divya said...

Were a gaggle of volunteers as well as starting off a brand new gumption within a community. Your blog furnished us precious details to be effective on. You've got completed any amazing work!keep update
Ai & Artificial Intelligence Course in Chennai
PHP Training in Chennai
Ethical Hacking Course in Chennai Blue Prism Training in Chennai
UiPath Training in Chennai

Cho co said...

Plus, it will empower you with data management technologies like machine learning, Flume, and Hadoop. 360DigiTMG data science course in hyderabad

Revathi said...

I am really happy to read this blog!!keep it up!!

android training in chennai

android online training in chennai

android training in bangalore

android training in hyderabad

android Training in coimbatore

android training

android online training

erectile dysfunction causes said...

Hi there to every one, the contents present at this web page are genuinely remarkable for people experience, well, keep up the good work fellows.

EXCELR said...

"Thanks for the Information.Interesting stuff to read.Great Article.
I enjoyed reading your post, very nice share.data science training"

Madhan kumar said...

Hey, Wow all the posts are very informative for the people who visit this site. Good work! We also have a Website. Please feel free to visit our site. Thank you for sharing.
Be Your Own Boss! If you're looking for a change in your work prospects, then let's prepare for your career from here!!!
Self Employment | Women Development | Information Technology | Engineering Courses

tech said...

bookmarked!!, I like your site! best interiors

Farhan.Jee said...

Salesforce is a multi-tenant environment which provides an environment that suits your company's business needs. Salesforce training in India

Ratana said...

I'am glad to read the whole content of this blog and am very excited,Thank you for sharing good topic.
ហ្គេមបាញ់ត្រី​ UFA88

Ramesh Sampangi said...

AI Patasala offers the best career choice for aspirants who are looking for a data science career. Attend the AI Patasala Data Science Course Training program to crack your data science dream job.
Data Science Online Training in Hyderabad

Block said...

Thanks a lot very much for the high quality and results-oriented help.
I won’t think twice to endorse your blog post to anybody who wants
and needs support about this area.
Unix classes in Chennai
Best IT training institute in Chennai

360DigiTMG said...

Excellent effort to make this blog more wonderful and attractive.
data science classes in hyderabad