{"id":283,"date":"2011-07-28T12:32:19","date_gmt":"2011-07-28T12:32:19","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2011\/07\/28\/using-matlab-structures-in-c-with-builder-ne\/"},"modified":"2016-08-04T08:40:30","modified_gmt":"2016-08-04T13:40:30","slug":"using-matlab-structures-in-c-with-builder-ne","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2011\/07\/28\/using-matlab-structures-in-c-with-builder-ne\/","title":{"rendered":"Using MATLAB Structures in C# with Builder NE"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\r\n   <introduction>\r\n      <p>Guest blogger <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/4660\">Peter Webb<\/a> returns with another in an <a href=\"https:\/\/blogs.mathworks.com\/loren\/category\/deployment\/\">occasional series<\/a> of postings about application deployment.\r\n      <\/p>\r\n   <\/introduction>\r\n   <h3>Contents<\/h3>\r\n   <div>\r\n      <ul>\r\n         <li><a href=\"#1\">Structures Simplify Your Interfaces<\/a><\/li>\r\n         <li><a href=\"#2\">Declaring MATLAB-Compatible Structures in C#<\/a><\/li>\r\n         <li><a href=\"#3\">Passing Structures between MATLAB and C#<\/a><\/li>\r\n         <li><a href=\"#4\">Building and Running the Example<\/a><\/li>\r\n         <li><a href=\"#5\">How Does Your Code Use Structures?<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>Structures Simplify Your Interfaces<a name=\"1\"><\/a><\/h3>\r\n   <p>To demonstrate how to use structures in an <a href=\"http:\/\/en.wikipedia.org\/wiki\/C_Sharp_%28programming_language%29\">C#<\/a> application deployed with Builder NE, I've written a <a href=\"https:\/\/www.mathworks.com\/products\/matlab\/\">MATLAB<\/a> <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011a\/techdoc\/\/ref\/function.html\">function<\/a> to compute the time it takes a planet to orbit around the sun. <tt>computeOrbit<\/tt> needs <a href=\"http:\/\/www.braeunig.us\/space\/orbmech.htm#motions\">three pieces of information<\/a> about a planet: the planet's name, its mass, and its distance from the sun. It returns the planet's name and the orbital\r\n      period. By grouping the input and output data into structures, I can give <tt>computeOrbit<\/tt> a very simple interface:\r\n   <\/p><pre>function orbit = computeOrbit(planet)<\/pre><p>To compute the length of the Martian year, pass in this <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2011a\/techdoc\/\/matlab_prog\/br04bw6-38.html#br1ut1_\">MATLAB structure<\/a>:\r\n   <\/p><pre>planet.name = 'Mars';\r\nplanet.mass = 6.4185e+023;\r\nplanet.smAxis = 2.2792e+011<\/pre><p><tt>computeOrbit<\/tt> returns a structure with two fields:\r\n   <\/p><pre>name: 'Mars'\r\nperiod: 686.88<\/pre><p>And because it's a MATLAB function, if you give <tt>computeOrbit<\/tt> a vector of planets, it returns a vector of orbits. I'd like my <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/87d83y5b%28v=vs.80%29.aspx\">C# interface<\/a> to <tt>computeOrbit<\/tt> to take and return the same kind of structures. For example, if you create a structure array <tt>planets<\/tt> with data for the four inner planets, <tt>computeOrbit<\/tt> will return a structure array:\r\n   <\/p><pre> &gt;&gt; [planets(1:4).name] = deal('Mercury', 'Venus', 'Earth', 'Mars');\r\n &gt;&gt; [planets.mass] = deal(3.3020e+023, 4.8685e+024, 5.9736e+024, ...\r\n                          6.4185e+023);\r\n &gt;&gt; [planets.smAxis] = deal(5.7910e+010, 1.0821e+011, 1.4960e+011, ...\r\n                           2.2792e+011);\r\n &gt;&gt; orbits = computeOrbit(planets);\r\n &gt;&gt; orbits(3)<\/pre><pre> ans =<\/pre><pre>    name: 'Earth'\r\n  period: 365.2641<\/pre><h3>Declaring MATLAB-Compatible Structures in C#<a name=\"2\"><\/a><\/h3>\r\n   <p>The C# interface needs two structures: <tt>Planet<\/tt> and <tt>Orbit<\/tt>. To prevent conflict with similarly named types in other components, I've placed these types in a <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/z2kcy19k%28v=vs.80%29.aspx\">C# <i>namespace<\/i><\/a>, <tt>Uranometria<\/tt> (derived from Greek, it means \"measuring the sky\"). For convenience, I also provided the C# <tt>Planet<\/tt> structure with a <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ace5hbzh.aspx\">constructor<\/a>, but this is not strictly necessary.\r\n   <\/p><pre>namespace Uranometria\r\n{\r\n  public struct Planet\r\n  {\r\n      public string name;\r\n      public double mass;\r\n      public double smAxis;\r\n      public Planet(string n, double m, double sma)\r\n        { name = n; mass = m; smAxis = sma; }\r\n  }<\/pre><pre>  public struct Orbit\r\n  {\r\n      public string name;\r\n      public double period;\r\n  }\r\n}<\/pre><p>Builder NE will only automatically marshall structure data between identical structures: the C# and MATLAB field names must\r\n      be exactly the same and the corresponding field data types must be compatible. Here, compatible means conversion from one\r\n      type to the other occurs without loss of information. Compatibility is an ordered relationship: conversion from integer to\r\n      double preserves information, but conversion from double to integer might not. C#'s <tt>System.Int32<\/tt> is therefore compatible with MATLAB's <tt>double<\/tt>, but not vice-versa.\r\n   <\/p>\r\n   <p>Use the <tt>Orbit<\/tt> and <tt>Planet<\/tt> types to define the C# signature of the C# interface function <tt>computeOrbit<\/tt>:\r\n   <\/p><pre>public interface IOrbit\r\n{\r\n   Uranometria.Orbit[] computeOrbit(Uranometria.Planet[] p);\r\n}<\/pre><p>Since the MATLAB function <tt>computeOrbit<\/tt> takes and returns structure arrays, the C# <tt>computeOrbit<\/tt> interface function specifies arrays of structures for both the input and output parameters.\r\n   <\/p>\r\n   <h3>Passing Structures between MATLAB and C#<a name=\"3\"><\/a><\/h3>\r\n   <p>In C#, declare an array of <tt>Planet<\/tt> structures:\r\n   <\/p><pre>Uranometria.Planet[] planet = new Uranometria.Planet[4];<\/pre><p>I've qualified the type <tt>Planet<\/tt> with its namespace because I think it makes the type name clearer. But you could remove the qualification with a <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/sf0df423%28v=vs.80%29.aspx\"><tt>using<\/tt> directive<\/a>.\r\n   <\/p>\r\n   <p>Next, add some data (here, the data for Mercury) to the the array, using the convenience constructor:<\/p><pre>planet[0] = new Uranometria.Planet(\"Mercury\", 3.3020e+023,\r\n                                   5.7910e+010);<\/pre><p>Create an instance of the <tt>OrbitalMechanics<\/tt> component. This initializes the compenent and starts the MCR.\r\n   <\/p><pre>IOrbit o = new Uranometria.OrbitalMechanicsIOrbit();<\/pre><p>Call the <tt>computeOrbit<\/tt> MATLAB function, passing it the array of planets:\r\n   <\/p><pre>Uranometria.Orbit[] orbit = o.computeOrbit(planet);<\/pre><p><tt>computeOrbit<\/tt> returns an array of <tt>Orbit<\/tt> data. Iterate over the array, printing the <tt>name<\/tt> and <tt>period<\/tt> of each planetary orbit.\r\n   <\/p><pre>foreach (var p in orbit)\r\n  System.Console.WriteLine(\"{0,-7}  {1,6:f} days\", p.name, p.period);<\/pre><h3>Building and Running the Example<a name=\"4\"><\/a><\/h3>\r\n   <p>First, <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/31293-using-matlab-structures-in-c--with-builder-ne\">download the example code<\/a> from MATLAB Central. The download consists of the <tt>computeOrbit<\/tt> MATLAB function and a Visual Studio project that builds an application which calls <tt>computeOrbit<\/tt>. To build the example, you'll need to:\r\n   <\/p>\r\n   <li>Build the <tt>IOrbit<\/tt> interface DLL in Visual Studio\r\n   <\/li>\r\n   <li>Create a <tt>deploytool<\/tt> project that builds <tt>computeOrbit<\/tt> into a .NET  assembly.\r\n   <\/li>\r\n   <li>Build the C# application that calls <tt>computeOrbit<\/tt> through the  <tt>IOrbit<\/tt> interface.\r\n   <\/li>\r\n   <p>The file <tt>ReadmeStructures.txt<\/tt> contains detailed instructions.\r\n   <\/p>\r\n   <p>The downloaded files compile into <tt>Orrery.exe<\/tt>, which computes the orbital period of the four inner planets. Run from the DOS command line (make sure you've got your runtime\r\n      environment set up correctly), it produces a four-row table:\r\n   <\/p><pre>Planet   Period\r\n---------------\r\nMercury   87.97 days\r\nVenus    224.70 days\r\nEarth    365.26 days\r\nMars     686.88 days<\/pre><p>To compute the orbits of other planets, add <a href=\"http:\/\/nssdc.gsfc.nasa.gov\/planetary\/factsheet\/\">more data<\/a> to the array of <tt>Planet<\/tt> structures in <tt>Orrery.cs<\/tt> and rebuild the C# main application. There's no need to recompile the <tt>computeOrbit<\/tt> function.\r\n   <\/p>\r\n   <h3>How Does Your Code Use Structures?<a name=\"5\"><\/a><\/h3>\r\n   <p>Let me know about how your C# programs use MATLAB structures. Is this how you'd expect to pass structures between C# and MATLAB\r\n      programs? Let me know  <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=283#respond\">here<\/a>.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_f35a144281b845388584d4305fb17b80() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='f35a144281b845388584d4305fb17b80 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' f35a144281b845388584d4305fb17b80';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        author = 'Peter Webb';\r\n        copyright = 'Copyright 2011 The MathWorks, Inc.';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('<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');\r\n      \r\n      d.title = title + ' (MATLAB code)';\r\n      d.close();\r\n      }   \r\n      \r\n-->\r\n<\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_f35a144281b845388584d4305fb17b80()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n            the MATLAB code \r\n            <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; 7.12<br><\/p>\r\n<\/div>\r\n<!--\r\nf35a144281b845388584d4305fb17b80 ##### SOURCE BEGIN #####\r\n%% Using MATLAB Structures in C# with Builder NE\r\n% Guest blogger \r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/4660 \r\n% Peter Webb> returns with another in an \r\n% <https:\/\/blogs.mathworks.com\/loren\/category\/deployment\/ occasional series>\r\n% of postings about application deployment. \r\n\r\n%% Structures Simplify Your Interfaces\r\n% To demonstrate how to use structures in an \r\n% <http:\/\/en.wikipedia.org\/wiki\/C_Sharp_%28programming_language%29 C#>\r\n% application deployed with \r\n% <https:\/\/www.mathworks.com\/products.htmlbuilderne Builder NE>, \r\n% I've written a <https:\/\/www.mathworks.com\/products\/matlab\/ MATLAB>\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2011a\/techdoc\/\/ref\/function.html function>\r\n% to compute the time it takes \r\n% a planet to orbit around the sun. |computeOrbit| needs\r\n% <http:\/\/www.braeunig.us\/space\/orbmech.htm#motions three pieces of \r\n% information> about a planet: the planet's name, its mass, and its \r\n% distance from the sun. It returns the planet's name and the orbital period.\r\n% By grouping the input and output data into structures, I can give \r\n% |computeOrbit| a very simple interface:\r\n% \r\n%  function orbit = computeOrbit(planet)\r\n% \r\n% To compute the length of the Martian year, pass in this \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2011a\/techdoc\/\/matlab_prog\/br04bw6-38.html#br1ut1_ \r\n% MATLAB structure>:\r\n% \r\n%  planet.name = 'Mars';\r\n%  planet.mass = 6.4185e+023;\r\n%  planet.smAxis = 2.2792e+011\r\n%\r\n% |computeOrbit| returns a structure with two fields:\r\n% \r\n%  name: 'Mars'\r\n%  period: 686.88\r\n% \r\n% And because it's a MATLAB function, if you give |computeOrbit| a vector\r\n% of planets, it returns a vector of orbits. I'd like my \r\n% <http:\/\/msdn.microsoft.com\/en-us\/library\/87d83y5b%28v=vs.80%29.aspx \r\n% C# interface> to \r\n% |computeOrbit| to take and return the same kind of structures. For\r\n% example, if you create a structure array |planets| with data for the \r\n% four inner planets, |computeOrbit| will return a structure array:\r\n%\r\n%   >> [planets(1:4).name] = deal('Mercury', 'Venus', 'Earth', 'Mars');\r\n%   >> [planets.mass] = deal(3.3020e+023, 4.8685e+024, 5.9736e+024, ...\r\n%                            6.4185e+023);\r\n%   >> [planets.smAxis] = deal(5.7910e+010, 1.0821e+011, 1.4960e+011, ...\r\n%                             2.2792e+011);\r\n%   >> orbits = computeOrbit(planets);\r\n%   >> orbits(3)\r\n%\r\n%   ans = \r\n%\r\n%      name: 'Earth'\r\n%    period: 365.2641\r\n\r\n%% Declaring MATLAB-Compatible Structures in C#\r\n% The C# interface needs two structures: |Planet| and |Orbit|. To prevent\r\n% conflict with similarly named types in other components, I've placed these\r\n% types in a \r\n% <http:\/\/msdn.microsoft.com\/en-us\/library\/z2kcy19k%28v=vs.80%29.aspx C# \r\n% _namespace_>, |Uranometria| (derived from Greek, it means\r\n% \"measuring the sky\"). For convenience, I also provided the C#\r\n% |Planet| structure with a \r\n% <http:\/\/msdn.microsoft.com\/en-us\/library\/ace5hbzh.aspx constructor>,\r\n% but this is not strictly necessary.\r\n%\r\n%  namespace Uranometria\r\n%  {\r\n%    public struct Planet\r\n%    {\r\n%        public string name;\r\n%        public double mass;\r\n%        public double smAxis;\r\n%        public Planet(string n, double m, double sma) \r\n%          { name = n; mass = m; smAxis = sma; }\r\n%    }\r\n%\r\n%    public struct Orbit\r\n%    {\r\n%        public string name;\r\n%        public double period;\r\n%    }\r\n%  }\r\n%\r\n% Builder NE will only automatically marshall structure data between \r\n% identical structures: the C# and MATLAB field names must be exactly the\r\n% same and the corresponding field data types must be compatible. Here,\r\n% compatible means conversion from one type to the other occurs without\r\n% loss of information. Compatibility is an ordered relationship: conversion\r\n% from integer to double preserves information, but conversion from double\r\n% to integer might not. C#'s |System.Int32| is therefore compatible with\r\n% MATLAB's |double|, but not vice-versa. \r\n%\r\n% Use the |Orbit| and |Planet| types to define the C#\r\n% signature of the C# interface function |computeOrbit|:\r\n%\r\n%  public interface IOrbit\r\n%  {\r\n%     Uranometria.Orbit[] computeOrbit(Uranometria.Planet[] p);\r\n%  }\r\n%\r\n% Since the MATLAB function |computeOrbit| takes and returns structure\r\n% arrays, the C# |computeOrbit| interface function specifies arrays of \r\n% structures for both the input and output parameters. \r\n\r\n%% Passing Structures between MATLAB and C#\r\n% In C#, declare an array of |Planet| structures:\r\n% \r\n%  Uranometria.Planet[] planet = new Uranometria.Planet[4];\r\n%\r\n% I've qualified the \r\n% type |Planet| with its namespace because I think it makes the type name\r\n% clearer. But you could remove the qualification with a \r\n% <http:\/\/msdn.microsoft.com\/en-us\/library\/sf0df423%28v=vs.80%29.aspx \r\n% |using| directive>.\r\n% \r\n% Next, add some data (here, the data for Mercury) to the the array, using\r\n% the convenience constructor:\r\n%\r\n%  planet[0] = new Uranometria.Planet(\"Mercury\", 3.3020e+023, \r\n%                                     5.7910e+010);\r\n%\r\n% Create an instance of the |OrbitalMechanics| component. This initializes\r\n% the compenent and starts the MCR.\r\n%\r\n%  IOrbit o = new Uranometria.OrbitalMechanicsIOrbit();\r\n%\r\n% Call the |computeOrbit| MATLAB function, passing it the array of planets:\r\n%\r\n%  Uranometria.Orbit[] orbit = o.computeOrbit(planet);\r\n%\r\n% |computeOrbit| returns an array of |Orbit| data. Iterate over the array,\r\n% printing the |name| and |period| of each planetary orbit.\r\n%\r\n%  foreach (var p in orbit)\r\n%    System.Console.WriteLine(\"{0,-7}  {1,6:f} days\", p.name, p.period);\r\n\r\n%% Building and Running the Example\r\n% First, \r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/31293-using-matlab-structures-in-c--with-builder-ne \r\n% download the example code> from MATLAB Central. The download\r\n% consists of the |computeOrbit| MATLAB function and a Visual Studio\r\n% project that builds an application which calls |computeOrbit|. To build\r\n% the example, you'll need to:\r\n%\r\n% # Build the |IOrbit| interface DLL in Visual Studio\r\n% # Create a |deploytool| project that builds |computeOrbit| into a .NET\r\n%  assembly.\r\n% # Build the C# application that calls |computeOrbit| through the\r\n%  |IOrbit| interface.\r\n%\r\n% The file |ReadmeStructures.txt| contains detailed instructions.\r\n%\r\n% The downloaded files compile into |Orrery.exe|, which computes the\r\n% orbital period of the four inner planets. Run from the DOS command line\r\n% (make sure you've got your runtime environment set up correctly), it\r\n% produces a four-row table:\r\n%\r\n%  Planet   Period\r\n%  REPLACE_WITH_DASH_DASHREPLACE_WITH_DASH_DASHREPLACE_WITH_DASH_DASHREPLACE_WITH_DASH_DASHREPLACE_WITH_DASH_DASHREPLACE_WITH_DASH_DASHREPLACE_WITH_DASH_DASH-\r\n%  Mercury   87.97 days\r\n%  Venus    224.70 days\r\n%  Earth    365.26 days\r\n%  Mars     686.88 days\r\n%\r\n% To compute the orbits of other planets, add \r\n% <http:\/\/nssdc.gsfc.nasa.gov\/planetary\/factsheet\/ more data> to the array \r\n% of |Planet| structures in |Orrery.cs| and rebuild the C# main application.\r\n% There's no need to recompile the |computeOrbit| function.\r\n\r\n%% How Does Your Code Use Structures?\r\n% Let me know about how your C# programs use MATLAB structures. Is this\r\n% how you'd expect to pass structures between C# and MATLAB programs? Let\r\n% me know  <https:\/\/blogs.mathworks.com\/loren\/?p=283#respond here>.\r\n\r\n##### SOURCE END ##### f35a144281b845388584d4305fb17b80\r\n-->","protected":false},"excerpt":{"rendered":"<p>\r\n   \r\n      Guest blogger Peter Webb returns with another in an occasional series of postings about application deployment.\r\n      \r\n   \r\n   Contents\r\n   \r\n      \r\n   ... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2011\/07\/28\/using-matlab-structures-in-c-with-builder-ne\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[24],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/283"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/comments?post=283"}],"version-history":[{"count":1,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/283\/revisions"}],"predecessor-version":[{"id":1947,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/283\/revisions\/1947"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=283"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=283"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=283"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}