{"id":9422,"date":"2018-02-09T09:00:46","date_gmt":"2018-02-09T14:00:46","guid":{"rendered":"https:\/\/blogs.mathworks.com\/pick\/?p=9422"},"modified":"2019-10-08T10:43:06","modified_gmt":"2019-10-08T14:43:06","slug":"a-classy-matlab-wrapper-for-your-c","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/pick\/2018\/02\/09\/a-classy-matlab-wrapper-for-your-c\/","title":{"rendered":"A Classy MATLAB Wrapper for your C++"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\n   <introduction><\/p>\n<p><a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/32620\">Greg&#8217;s<\/a> pick this week is <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/38964-example-matlab-class-wrapper-for-a-c++-class\">Example MATLAB class wrapper for a C++ class<\/a> by <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/1073021-oliver-woodford\">Oliver Woodford<\/a>.\n      <\/p>\n<p>You have a C++ class that you would like to instantiate in MATLAB.<\/p>\n<p>If you are using MATLAB R2019a or later: Check out <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/call-cpp-library-functions.html\">Directly calling C++ libraries from MATLAB<\/a><\/p>\n<p>If you are using R2018b or earlier release, you cannot call C++ code directly in MATLAB and it needs to be imported via a MEX-File.<\/p>\n<p>However <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2017b\/matlab\/call-mex-files-1.html\">MEX-files<\/a> can only provide a function interface to MATLAB, and you want to instantiate an object from a class. Now what do you do?\n      <\/p>\n<p>Oliver Woodford comes to the rescue with a splendid example of how to wrap up your C++ class so you can instantiate it and<br \/>\n         maintain it from MATLAB.\n      <\/p>\n<p><b>Spoiler:<\/b> I used this to export a Simulink model as a MATLAB Class.\n      <\/p>\n<p>   <\/introduction><\/p>\n<h3>Contents<\/h3>\n<div>\n<ul>\n<li><a href=\"#1\">A Nifty MEX-wrapper to Interface With the Class<\/a><\/li>\n<li><a href=\"#2\">Why All the Complexity? What Does this Solve?<\/a><\/li>\n<li><a href=\"#3\">Deploy a Simulink Model as a MATLAB Class<\/a><\/li>\n<li><a href=\"#7\">What do you think?<\/a><\/li>\n<\/ul><\/div>\n<h3>A Nifty MEX-wrapper to Interface With the Class<a name=\"1\"><\/a><\/h3>\n<p>Since MEX-files only support function based interfaces, we need to create a wrapper function that enables<\/p>\n<div>\n<ul>\n<li>Instantiating the C++ class as an object<\/li>\n<li>Calling methods on that object (or changing property values)<\/li>\n<li>Destroying the object<\/li>\n<\/ul><\/div>\n<p>To employ the different methods of the C++ class, the first input argument to the MEX-function is used to identify which method<br \/>\n      of the C++ class is to be called.\n   <\/p>\n<p><b>MEX-code<\/b><\/p>\n<pre>\r\n   <p><tt>void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])<\/tt><\/p>\r\n   <p>{\t<\/p>\r\n   <p>    \/\/ Get the command string<\/p>\r\n   <p>    char methodId[64];<\/p>\r\n   <p>    mxGetString(prhs[0], methodId, sizeof(methodId))<\/p>\r\n   <p>    mexPrintf(&#8220;***Method Id: %s\\n&#8221;, methodId);<\/p>\r\n   <p><tt>}<\/tt><\/p>\r\n   <\/pre>\n<p><b>MATLAB Code:<\/b><\/p>\n<p><tt>&gt;&gt; out = myMexFunction(&#8216;myMethod&#8217;, in);<\/tt><\/p>\n<p><tt>***Method Id: myMethod<\/tt><\/p>\n<p><tt>&gt;&gt; <\/tt><\/p>\n<p>The additional arguments of the MEX-function are used as inputs to the C++ class methods.<\/p>\n<p>Once the MEX-function wrapper is in place and compiled, a MATLAB Class is created that mirrors the C++ class, and which uses<br \/>\n      the MEX-function wrapper to map the various properties and methods of the MATLAB Class to the C++ class.\n   <\/p>\n<h3>Why All the Complexity? What Does this Solve?<a name=\"2\"><\/a><\/h3>\n<p>There are three key elements that make this entry excellent.<\/p>\n<div>\n<ol>\n<li>It demonstrates how to use the C++ code &#8220;safely&#8221; in the context of the MEX-function<\/li>\n<li>It includes a helper file with several utilities that make part 1 easy.<\/li>\n<li>It provides an example to use as a template for your own project<\/li>\n<\/ol><\/div>\n<p>The tricky part about using a C++ class comes when you want to have multiple instances of the class persist between calls<br \/>\n      to the MEX-function wrapper.  If we&#8217;re not careful, we could introduce <a href=\"https:\/\/en.wikipedia.org\/wiki\/Memory_leak\">memory leaks<\/a>.\n   <\/p>\n<p>This is where Oliver&#8217;s entry shines.  He exports a reference to the class instance back to MATLAB so its lifecycle can be<br \/>\n      synchronized with the lifecycle of a MATLAB Class instance.\n   <\/p>\n<p>That&#8217;s what this line:<\/p>\n<p><pre>    plhs[0] = convertPtr2Mat&lt;CPP_CLASSNAME&gt;(new CPP_CLASSNAME);<\/pre>\n<\/p>\n<p>does when creating a new instance of the C++ class. A handle to the new object is output from the MEX-function as a 64-bit<br \/>\n      integer.\n   <\/p>\n<p>This handle can then be used to refer to that particular instance of the C++ class from MATLAB.  Therefore you see references<br \/>\n      to\n   <\/p>\n<pre>    objectHandle =  prhs[1];<p>    CPP_CLASSNAME *cppObj = convertMat2Ptr&lt;CPP_CLASSNAME&gt;(objectHandle);<\/p><\/pre>\n<p>which convert the 64-bit integer handle that MATLAB uses back to the native C++ class inside the MEX-function.<\/p>\n<h3>Deploy a Simulink Model as a MATLAB Class<a name=\"3\"><\/a><\/h3>\n<p>To try out this entry, I used Simulink Coder to generate a C++ class for a Simulink model<\/p>\n<p><a href=\"https:\/\/blogs.mathworks.com\/pick\/files\/simpleModel20180208.png\"><img decoding=\"async\" loading=\"lazy\" width=\"300\" height=\"170\" src=\"https:\/\/blogs.mathworks.com\/pick\/files\/simpleModel20180208-300x170.png\" alt=\"\" class=\"alignnone size-medium wp-image-9432\" \/><\/a><\/p>\n<p>This simple model was configured to generate C++ as code as a C++ class.<\/p>\n<p><a href=\"https:\/\/blogs.mathworks.com\/pick\/files\/modelConfig20180208.png\"><img decoding=\"async\" loading=\"lazy\" width=\"300\" height=\"85\" src=\"https:\/\/blogs.mathworks.com\/pick\/files\/modelConfig20180208-300x85.png\" alt=\"\" class=\"alignnone size-medium wp-image-9434\" \/><\/a><\/p>\n<p>This encapsulates the generated code providing methods for initializing, stepping the model at each sample time, and terminating<br \/>\n      the execution of the model.\n   <\/p>\n<p>I did not use the default main function, but instead copied MATLAB_ROOT\/rtw\/c\/src\/common\/rt_cppclass_main.cpp as a new CPP-file and changed the <tt>main<\/tt> function to a <tt>mexFunction<\/tt> based on Oliver&#8217;s example <tt>class_interface_mex.cpp<\/tt>.\n   <\/p>\n<p>The corresponding MATLAB Class I wrote looked like this:<\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">type(<span style=\"color: #A020F0\">'basicSisoSystemInterface.m'<\/span>)<\/pre>\n<pre style=\"font-style:oblique\">\r\n%CLASS_INTERFACE Example MATLAB class wrapper to an underlying C++ class\r\nclassdef basicSisoSystemInterface &lt; handle\r\n    properties (SetAccess = private, Hidden = true)\r\n        ObjectHandle; % Handle to the underlying C++ class instance\r\n    end\r\n    methods\r\n        %% Constructor - Create a new C++ class instance \r\n        function this = basicSisoSystemInterface(varargin)\r\n            this.ObjectHandle = basicSisoSystem_mex('new', varargin{:});\r\n        end\r\n        \r\n        %% Destructor - Destroy the C++ class instance\r\n        function delete(this)\r\n            basicSisoSystem_mex('delete', this.ObjectHandle);\r\n        end\r\n\r\n        %% sim - an example class method call\r\n        function varargout = sim(this, varargin)\r\n            [varargout{1:nargout}] = basicSisoSystem_mex('sim', this.ObjectHandle, varargin{:});\r\n        end\r\n\r\n    end\r\nend\r\n<\/pre>\n<p>Where I included a method called &#8220;sim&#8221; to execute the C++ version of the model.<\/p>\n<p>Now I can call two different instances of the same model. In this case with different inputs.<\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">modelObj1 = basicSisoSystemInterface;\r\nmodelObj2 = basicSisoSystemInterface;\r\nout1 = sim(modelObj1, 3*ones(100, 1));\r\nout2 = sim(modelObj2, 5*ones(100, 1));\r\nplot(out1)\r\nhold <span style=\"color: #A020F0\">on<\/span>\r\nplot(out2)\r\ntitle(<span style=\"color: #A020F0\">'Multiple Instance model outputs'<\/span>)\r\nxlabel(<span style=\"color: #A020F0\">'Time (ms)'<\/span>)\r\nylabel(<span style=\"color: #A020F0\">'Model Output'<\/span>)\r\nlegend(<span style=\"color: #A020F0\">'Model Instance 1'<\/span>, <span style=\"color: #A020F0\">'Model Instance 2'<\/span>)\r\ngrid <span style=\"color: #A020F0\">on<\/span><\/pre>\n<p><a href=\"https:\/\/blogs.mathworks.com\/pick\/files\/writeUp_export_01.png\"><img decoding=\"async\" loading=\"lazy\" width=\"300\" height=\"225\" src=\"https:\/\/blogs.mathworks.com\/pick\/files\/writeUp_export_01-300x225.png\" alt=\"\" class=\"alignnone size-medium wp-image-9438\" \/><\/a> <\/p>\n<h3>What do you think?<a name=\"7\"><\/a><\/h3>\n<p>Let us know <a href=\"https:\/\/blogs.mathworks.com\/pick\/?p=9422#respond\">here<\/a>.\n   <\/p>\n<p><script language=\"JavaScript\">\n<!--\n\n    function grabCode_8728defe6a704c88a2d562e5690d2073() {\n        \/\/ Remember the title so we can use it in the new page\n        title = document.title;\n\n        \/\/ Break up these strings so that their presence\n        \/\/ in the Javascript doesn't mess up the search for\n        \/\/ the MATLAB code.\n        t1='8728defe6a704c88a2d562e5690d2073 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 8728defe6a704c88a2d562e5690d2073';\n    \n        b=document.getElementsByTagName('body')[0];\n        i1=b.innerHTML.indexOf(t1)+t1.length;\n        i2=b.innerHTML.indexOf(t2);\n \n        code_string = b.innerHTML.substring(i1, i2);\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\n\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \n        \/\/ in the XML parser.\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\n        \/\/ doesn't go ahead and substitute the less-than character. \n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\n\n        author = '';\n        copyright = 'Copyright 2018 The MathWorks, Inc.';\n\n        w = window.open();\n        d = w.document;\n        d.write('\n\n<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add author and copyright lines at the bottom if specified.\r\n        if ((author.length > 0) || (copyright.length > 0)) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (author.length > 0) {\r\n                d.writeln('% _' + author + '_');\r\n            }\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\n\n\\n');\n      \n      d.title = title + ' (MATLAB code)';\n      d.close();\n      }   \n      \n-->\n<\/script><\/p>\n<p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><a href=\"javascript:grabCode_8728defe6a704c88a2d562e5690d2073()\"><span style=\"font-size: x-small;        font-style: italic;\">Get<br \/>\n            the MATLAB code<br \/>\n            <noscript>(requires JavaScript)<\/noscript><\/span><\/a><\/p>\n<p>      Published with MATLAB&reg; R2017b<\/p>\n<\/div>\n<p><!--\n8728defe6a704c88a2d562e5690d2073 ##### SOURCE BEGIN #####\n%% A Classy MATLAB Wrapper for your C++\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/32620 Greg's> \n% pick this week is <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/38964-example-matlab-class-wrapper-for-a-c++-class \n% Example MATLAB class wrapper for a C++ class> by <https:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/1073021-oliver-woodford \n% Oliver Woodford>.\n% \n% You have a C++ class that you would like to instantiate in MATLAB.\n% \n% Since you cannot call C++ code directly in MATLAB it needs to be imported \n% so MEX is the answer\u00e2\u20ac\u00a6. right?\n% \n% Well yes, but <https:\/\/www.mathworks.com\/help\/releases\/R2017b\/matlab\/call-mex-files-1.html \n% MEX-files> can only provide a function interface to MATLAB, and you want to \n% instantiate an object from a class. Now what do you do?\n% \n% Oliver Woodford comes to the rescue with a splendid example of how to wrap \n% up your C++ class so you can instantiate it and maintain it from MATLAB.\n% \n% *Spoiler:* I used this to export a Simulink model as a MATLAB Class.\n%% A Nifty MEX-wrapper to Interface With the Class\n% Since MEX-files only support function based interfaces, we need to create \n% a wrapper function that enables \n% \n% * Instantiating the C++ class as an object\n% * Calling methods on that object (or changing property values)\n% * Destroying the object\n% \n% To employ the different methods of the C++ class, the first input argument \n% to the MEX-function is used to identify which method of the C++ class is to \n% be called.\n% \n% *MEX-code*\n% \n% |void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])|\n% \n% |{\t|\n% \n% |    \/\/ Get the command string|\n% \n% |    char methodId[64];|\n% \n% |    mxGetString(prhs[0], methodId, sizeof(methodId))|\n% \n% |    mexPrintf(\u00e2\u20ac\u0153***Method Id: %s\\n\u00e2\u20ac\ufffd, methodId);|\n% \n% |}|\n% \n% *MATLAB Code:*\n% \n% |>> out = myMexFunction(\u00e2\u20ac\u02dcmyMethod\u00e2\u20ac&#x2122;, in);|\n% \n% |***Method Id: myMethod|\n% \n% |>> |\n% \n% The additional arguments of the MEX-function are used as inputs to the \n% C++ class methods.\n% \n% Once the MEX-function wrapper is in place and compiled, a MATLAB Class \n% is created that mirrors the C++ class, and which uses the MEX-function wrapper \n% to map the various properties and methods of the MATLAB Class to the C++ class.\n%% Why All the Complexity? What Does this Solve?\n% There are three key elements that make this entry excellent. \n% \n% # It demonstrates how to use the C++ code \u00e2\u20ac\u0153safely\u00e2\u20ac\ufffd in the context of the MEX-function\n% # It includes a helper file with several utilities that make part 1 easy.\n% # It provides an example to use as a template for your own project\n% \n% The tricky part about using a C++ class comes when you want to have multiple \n% instances of the class persist between calls to the MEX-function wrapper.  If \n% we\u00e2\u20ac&#x2122;re not careful, we could introduce <https:\/\/en.wikipedia.org\/wiki\/Memory_leak \n% memory leaks>.\n% \n% This is where Oliver\u00e2\u20ac&#x2122;s entry shines.  He exports a reference to the class \n% instance back to MATLAB so it\u00e2\u20ac&#x2122;s lifecycle can by synchronized with the lifecycle \n% of a MATLAB Class instance.\n% \n% That\u00e2\u20ac&#x2122;s what this line:\n% \n% |    plhs[0] = convertPtr2Mat<CPP_CLASSNAME>(new CPP_CLASSNAME);|\n% \n% does when creating a new instance of the C++ class. A handle to the new \n% object is output from the MEX-function as a 64-bit integer.\n% \n% This handle can then be used to refer to that particular instance of the \n% C++ class from MATLAB.  Therefore you see references to\n% \n%         |objectHandle =  prhs[1];|\n% \n% |    CPP_CLASSNAME *cppObj = convertMat2Ptr<CPP_CLASSNAME>(objectHandle);|\n% \n% which convert the 64-bit integer handle that MATLAB uses back to the native \n% C++ class inside the MEX-function.\n%% Deploy a Simulink Model as a MATLAB Class\n% To try out this entry, I used Simulink Coder to generate a C++ class for a \n% Simulink model\n% \n%  \n% \n% This simple model was configured to generate C++ as code as a C++ class.  \n% \n% \n% \n% This encapsulates the generated code providing methods for initializing, \n% stepping the model at each sample time, and terminating the execution of the \n% model.\n% \n% I did not use the default main function, but instead copied |<MATLAB_ROOT>\/rtw\/c\/src\/common\/rt_cppclass_main.cpp| \n% as a new CPP-file and changed the |main| function to a |mexFunction| based on \n% Oliver's example |class_interface_mex.cpp|.\n% \n% The corresponding MATLAB Class I wrote looked like this:\n%%\ntype('basicSisoSystemInterface.m')\n%% \n% Where I included a method called \"sim\" to execute the C++ version of the \n% model.\n% \n% Now I can call two different instances of the same model. In this case \n% with different inputs.\n\nmodelObj1 = basicSisoSystemInterface;\nmodelObj2 = basicSisoSystemInterface;\nout1 = sim(modelObj1, 3*ones(100, 1));\nout2 = sim(modelObj2, 5*ones(100, 1));\nplot(out1)\nhold on\nplot(out2)\ntitle('Multiple Instance model outputs')\nxlabel('Time (ms)')\nylabel('Model Output')\nlegend('Model Instance 1', 'Model Instance 2')\ngrid on\n%% \n% \n%% What do you think?\n##### SOURCE END ##### 8728defe6a704c88a2d562e5690d2073\n--><\/p>\n","protected":false},"excerpt":{"rendered":"<div class=\"overview-image\"><img decoding=\"async\"  class=\"img-responsive\" src=\"https:\/\/blogs.mathworks.com\/pick\/files\/simpleModel20180208-300x170.png\" onError=\"this.style.display ='none';\" \/><\/div>\n<p>Greg&#8217;s pick this week is Example MATLAB class wrapper for a C++ class by Oliver Woodford.<\/p>\n<p>You have a C++ class that you would like to instantiate in MATLAB.<br \/>\nIf you are using MATLAB&#8230; <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/pick\/2018\/02\/09\/a-classy-matlab-wrapper-for-your-c\/\">read more >><\/a><\/p>\n","protected":false},"author":36,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[7,24],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/9422"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/users\/36"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/comments?post=9422"}],"version-history":[{"count":14,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/9422\/revisions"}],"predecessor-version":[{"id":9448,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/9422\/revisions\/9448"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/media?parent=9422"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/categories?post=9422"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/tags?post=9422"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}