How are the C and C++ Interfaces working?

1 view (last 30 days)
I worked with both MATLAB C++ Interface (clibgen package) and Matlabs C Interface (callib, loadlibrary, ...). Now, I am interested in getting to know how these interfaces are implemented:
Regarding the C++ interface:
I noticed that Matlab does not "really" call the C++ functions but builds a C interface DLL instead. To do this, the clibgen package reads the header files, creates a temporary C++ file and builds a shared library from it. The c++ file supplies a C interface as a proxy to call C++ functions via a C binary interface.
When all the prerequisites are done, the C++ functions can be used by prefixing them with "clib.packagename", e.g. clib.package.DoStuff(). I am particularly interested in how Matlab resolves the expression "clib.package.DoStuff" into a string key that can be passed to the "cppGetPassThrough" function. How does Matlab know what functions and classes are available in a DLL? 
Regarding the C interface:
I suspect that loading a DLL also invokes a call to some compiler. I am not entirely sure about but it might have something to do with compatibility to 64bit?

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 11 Nov 2021
Regarding the C++ interface:
C++ interface embeds an XML file into the shared library during the build step. This XML contains mappings between library constructs and the pass-throughs in the shared library. When you call “clib.packagename.foo”, MATLAB retrieves the XML from the shared library to find and call the pass-through in the shared library for construct 'foo'.  
 
Regarding the C interface:
Keep in mind that "loadlibrary" and "calllib" are legacy features for pure C libraries. Having said that, a thunk file is generated and built to adjust the MATLAB calling conventions to the native DLL calling conventions. Moving forward, it is highly recommended that new applications use the C++ Interface. The C++ Interface can generate and call a C library that has the appropriate extern C linkage for handling mangled names. 

More Answers (0)

Tags

No tags entered yet.

Products

Community Treasure Hunt

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

Start Hunting!