How do I use C++ classes in a mex file?

4 views (last 30 days)
George
George on 2 Mar 2012
Dear All,
I have a several header files and corresponding c++ files for classes that I have written for a C++ program. I would like to call methods in these classes from a mex file.
So, I have the C++ file that contains my mexFunction. In that file, I would like to instantiate an object from a class in a separate c++ file. How can I do that? Do I have to somehow "mex" the file that contains the separate class?
Thank you.

Answers (2)

Kaustubha Govind
Kaustubha Govind on 2 Mar 2012
You can instantiate it just like you would in any other C++ file. And yes, you will need to compile that class also into the MEX file. You can simply add the name of the .cpp file to the end of the MEX command.
>> mex mymexfile.cpp otherclass.cpp
  1 Comment
Mohamed Abdelkader Zahana
Thanks Kaustubha Govind . I tried your suggestion on MATLAB R2014b, Windows 8 64bit and it works!. Just wanted to mention that, so pther people facing the problem could benefit from it.

Sign in to comment.


Ken Atwell
Ken Atwell on 3 Mar 2012
While you can compile C++ code into a MEX file (see above), accessing methods will take a bit of work. You will still need to create a mexFunction API so MATLAB has something to call. You don't have any direct way of invoking C++ methods from MATLAB -- you might need to implement several mexFunction files to "wrap" the methods you need to call.
If that sounds like too much work and you are on Windows, you may want to look into adapting your C++ class into a .NET assembly -- unlike natively compiled C++, MATLAB can instantiate .NET classes and invoke methods.

Tags

Community Treasure Hunt

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

Start Hunting!