{"id":264,"date":"2011-02-03T20:23:12","date_gmt":"2011-02-03T20:23:12","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/2011\/02\/03\/creating-c-shared-libraries-and-dlls\/"},"modified":"2017-04-03T21:35:50","modified_gmt":"2017-04-04T02:35:50","slug":"creating-c-shared-libraries-and-dlls","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2011\/02\/03\/creating-c-shared-libraries-and-dlls\/","title":{"rendered":"Creating C++ Shared Libraries and DLLs"},"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=\"#2\">Building a Shared Library<\/a><\/li>\r\n         <li><a href=\"#3\">The Generated Interface<\/a><\/li>\r\n         <li><a href=\"#4\">Calling Functions in a Shared Library<\/a><\/li>\r\n         <li><a href=\"#5\">Creating and Running the Application<\/a><\/li>\r\n         <li><a href=\"#6\">Next: Using Multiple Shared Libraries<\/a><\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <p>A previous post demonstrated how to use <a href=\"https:\/\/www.mathworks.com\/products\/compiler\">MATLAB Compiler<\/a> to create <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/f7-996249.html\">standalone executables<\/a>. In this article, I'll demonstrate how to use MATLAB Compiler to create C and C++ <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/f2-995712.html\">shared libraries or DLLs<\/a>.\r\n   <\/p>\r\n   <p>You create a shared library or DLL to add MATLAB-based functionality to an application you're developing. You select one or\r\n      more MATLAB-based functions to include in the shared library, and MATLAB Compiler generates a binary file that you link against\r\n      your application. Shared libraries generated by MATLAB Compiler are compatible with the Microsoft Visual Studio development\r\n      environment on Windows and with the GNU C\/C++ tool suite on most UNIX platforms. The list of supported compilers changes from one release to the next; be sure to check that list before starting your project.\r\n   <\/p>\r\n   <h3>Building a Shared Library<a name=\"2\"><\/a><\/h3>\r\n   <p>To illustrate the process of creating and using shared libraries, I'll use a cryptographic algorithm, the <a href=\"http:\/\/en.wikipedia.org\/wiki\/Vigen%C3%A8re_cipher\">Vigenere cipher<\/a>. The program I've written consists of two parts:\r\n   <\/p>\r\n   <div>\r\n      <ul>\r\n         <li><tt>libvingenere<\/tt>: A shared library containing two MATLAB functions <tt>encrypt<\/tt> and <tt>decrypt<\/tt>.\r\n         <\/li>\r\n         <li><tt>vigenere.cpp<\/tt>: A C++ main program that calls the functions in <tt>libvigenere<\/tt>.\r\n         <\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <p>The <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/29443-deploying-a-shared-library\">source code<\/a> for the MATLAB functions and the main program is available on <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/\">MATLAB Central<\/a>. The download package also includes <tt>VigenereDetails.html<\/tt>, which describes the implementation of the Vigenere cipher in MATLAB.\r\n   <\/p>\r\n   <p>The <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/mcc.html\"><tt>mcc<\/tt><\/a> command invokes MATLAB Compiler both from within interactive MATLAB and at the system (DOS or UNIX shell) prompt. Use <tt>mcc<\/tt> to build a shared library from the MATLAB <tt>encrypt<\/tt> and <tt>decrypt<\/tt> MATLAB functions:\r\n   <\/p><pre> mcc -v -W cpplib:libvigenere -T link:lib encrypt decrypt<\/pre><p>This <tt>mcc<\/tt> command breaks down into four parts:\r\n   <\/p>\r\n   <div>\r\n      <ul>\r\n         <li><tt>-v<\/tt>: Turn on verbose output.\r\n         <\/li>\r\n         <li><tt>-W cpplib:libvigenere<\/tt>: Generate C++ wrapper code. Name the generated library <tt>libvigenere<\/tt>.\r\n         <\/li>\r\n         <li><tt>-T link:lib<\/tt>: Invoke a C\/C++ compiler to create a platform-specific binary shared library file from the generated code.\r\n         <\/li>\r\n         <li><tt>encrypt decrypt<\/tt>: Place the <tt>encrypt<\/tt> and <tt>decrypt<\/tt> functions in the shared library. Generate C++ wrapper functions for each.\r\n         <\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <p>This command generates several files. Two of them are relevant here:<\/p>\r\n   <div>\r\n      <ul>\r\n         <li><tt>libvigenere.dll<\/tt>: The platform-specific binary: the shared library itself. On most Unix systems, this file ends with a <tt>.so<\/tt> extension: <tt>libvigenere.so<\/tt>.\r\n         <\/li>\r\n         <li><tt>libvigenere.h<\/tt>: Declarations of the C++ wrapper functions and C++ type conversion classes and utilities.\r\n         <\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <h3>The Generated Interface<a name=\"3\"><\/a><\/h3>\r\n   <p>MATLAB Compiler generates many different <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/f2-998954.html\">kinds of functions<\/a>: initialization, termination, error and print handling and, of course, the <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/f10-999433.html\">functions you selected<\/a> to compile into the library.\r\n   <\/p>\r\n   <p>In our example, MATLAB Compiler generates a C++ entry point for <tt>encrypt<\/tt> and <tt>decrypt<\/tt>. Stripped of some bookkeeping annotation, these functions look very much like the corresponding MATLAB functions.\r\n   <\/p><pre>void encrypt(int nargout, mwArray&amp; ciphertext,\r\n             const mwArray&amp; plaintext, const mwArray&amp; key);<\/pre><pre>void decrypt(int nargout, mwArray&amp; plaintext,\r\n             const mwArray&amp; ciphertext, const mwArray&amp; key);<\/pre><p>The generated functions differ from the MATLAB functions in two significant ways:<\/p>\r\n   <div>\r\n      <ul>\r\n         <li>The C++ functions explicitly declare the types of their arguments.<\/li>\r\n         <li>The C++ functions return <tt>void<\/tt>, passing back results in output parameters provided in the argument list.\r\n         <\/li>\r\n      <\/ul>\r\n   <\/div>\r\n   <p>Let's look at the <tt>encrypt<\/tt> function in detail. For comparison, here's <tt>encrypt<\/tt>'s MATLAB <a href=\"http:\/\/en.wikipedia.org\/wiki\/Function_signature\">function signature<\/a>:\r\n   <\/p><pre> function ciphertext = encrypt(plaintext, key)<\/pre><p>The <tt>encrypt<\/tt> MATLAB function has one output and two inputs. The <tt>encrypt<\/tt> C++ function has zero outputs (the <tt>void<\/tt> return type) and four inputs. The first C++ input indicates the number of outputs requested by the caller. As indicated by\r\n      the MATLAB function, the number of outputs may be zero or one. Passing any other value will result in an error. The second\r\n      C++ input is the output argument, passed by reference. <tt>encrypt<\/tt> will overwrite any data in this argument with the encrypted message. The third and fourth C++ input arguments are the function\r\n      inputs, the plaintext and the encryption key. They are passed by <a href=\"http:\/\/en.wikipedia.org\/wiki\/Const-correctness\">constant reference<\/a> which means the <tt>encrypt<\/tt> function cannot change their contents.\r\n   <\/p>\r\n   <p>Unlike MATLAB, C++ requires all variables have declared, immutable types. Variables in MATLAB have types as well (matrix,\r\n      cell array, structure, etc.), but the type of a MATLAB variable can change at any time. To accommodate this dynamic behavior\r\n      in C++, the MATLAB Compiler provides the <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/f0-98564.html\"><tt>mwArray<\/tt><\/a> data type. All the functions generated by the MATLAB Compiler take <tt>mwArray<\/tt> inputs and return <tt>mwArray<\/tt> outputs. The <tt>mwArray<\/tt> API allows you to create <tt>mwArray<\/tt> objects from most C++ data types and to extract native C+++ data from a returned <tt>mwArray<\/tt>.\r\n   <\/p>\r\n   <h3>Calling Functions in a Shared Library<a name=\"4\"><\/a><\/h3>\r\n   <p>Now that I've created a shared library, I need to write a program to call the library's public functions. The program performs\r\n      six tasks:\r\n   <\/p>\r\n   <li>Includes the shared library's header file.<\/li>\r\n   <li>Parses command line arguments.<\/li>\r\n   <li><a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/mclinitializeapplication.html\">Initializes<\/a> the <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/f12-999353.html\">MATLAB Compiler Runtime<\/a>'s global state and the shared library's state.\r\n   <\/li>\r\n   <li>Creates input arguments; convert native C++ data types to <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/f0-98564.html\">MATLAB data types<\/a>.\r\n   <\/li>\r\n   <li>Invokes one or more functions from the shared library.<\/li>\r\n   <li><a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/mclterminateapplication.html\">Shuts down<\/a> the library and the MATLAB Compiler Runtime.\r\n   <\/li>\r\n   <p>Below, I demonstrate how these steps translate into the code of the example's main program, <tt>vigenere.cpp<\/tt>.\r\n   <\/p>\r\n   <p><b>Step 1<\/b>: All programs that use a MATLAB Compiler-generated shared library must include the library's header file. The header file\r\n      has the same base name as the compiled library, <tt>libvigenere<\/tt> in this case, and a <tt>.h<\/tt> extension.\r\n   <\/p><pre>\/\/ vingenere.cpp: Encrypt and decrypt using the Vigenere cipher.\r\n#include \"libvigenere.h\"\r\n#include &lt;iostream&gt;<\/pre><p><b>Step 2<\/b>: The main program parses the command line. The first argument, a switch, determines the type of action: <tt>-e<\/tt> means encrypt, <tt>-d<\/tt> decrypt. The second argument is the message, and the third, the key.\r\n   <\/p><pre>int main(int ac, const char *av[])\r\n{\r\n    \/\/ Encrypt or decrypt? Determined by command line switch\r\n    bool enc = strcmp(av[1], \"-e\") == 0;<\/pre><p><b>Step 3<\/b>: Initialize the runtime and start the library before calling any functions exported from the runtime or the library. Failure\r\n      to initialize will cause your program to crash. Always check for success (the initializers return <tt>false<\/tt> if they fail) and issue error messages as necessary.\r\n   <\/p><pre>    \/\/ Initialize the MATLAB Compiler Runtime global state\r\n    if (!mclInitializeApplication(NULL,0))\r\n    {\r\n        std::cerr &lt;&lt; \"Could not initialize the application properly.\"\r\n                  &lt;&lt; std::endl;\r\n        return -1;\r\n    }<\/pre><pre>    \/\/ Initialize the Vigenere library\r\n    if( !libvigenereInitialize() )\r\n    {\r\n        std::cerr &lt;&lt; \"Could not initialize the library properly.\"\r\n                  &lt;&lt; std::endl;\r\n        return -1;\r\n    }<\/pre><p><b>Step 4<\/b>: Convert the C++ strings from the command line (the message and the key) into MATLAB strings by creating mwArray objects.\r\n      These declarations <i>cannot<\/i> appear before the initialization calls in Step 3.\r\n   <\/p><pre>    \/\/ Must declare all MATLAB data types after initializing the\r\n    \/\/ application and the library, or their constructors will fail.\r\n    mwArray text(av[2]);\r\n    mwArray key(av[3]);\r\n    mwArray result;<\/pre><p><b>Step 5<\/b>: Invoke the exported functions. Encrypt or decrypt as indicated by the command line switch. Note that the C++ functions have\r\n      the same name as their MATLAB counterparts, and that all return values must be passed in by reference. The <tt>mwArray<\/tt> class defines\r\n   <\/p><pre>    \/\/ Initialization succeeded. Encrypt or decrypt.<\/pre><pre>    if (enc == true)\r\n    {\r\n        \/\/ Encrypt the plaintext text with the key.\r\n        \/\/ Request one output, pass in two inputs\r\n        encrypt(1, result, text, key);\r\n    }\r\n    else\r\n    {\r\n        \/\/ Decrypt the ciphertext text with the key.\r\n        \/\/ Request one output, pass in two inputs\r\n        decrypt(1, result, text, key);\r\n    }\r\n    std::cout &lt;&lt; result &lt;&lt; std::endl;<\/pre><p><b>Step 6<\/b>: Shut down the library and the runtime, in the opposite order of initialization (library first, then runtime).\r\n   <\/p><pre>    \/\/ Shut down the library and the application global state.\r\n    libvigenereTerminate();\r\n    mclTerminateApplication();\r\n}<\/pre><h3>Creating and Running the Application<a name=\"5\"><\/a><\/h3>\r\n   <p>MATLAB Compiler uses the <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/mbuild.html\"><tt>mbuild<\/tt><\/a> function to compile the code it generates into a shared library. <tt>mbuild<\/tt> knows how to invoke the C\/C++ compiler with the correct switches so the compiler can find the required include files and\r\n      libraries. You can use <tt>mbuild<\/tt> to create your own executables and link them with MATLAB Compiler-generated shared libraries. On Windows, for example, issue\r\n      this command:\r\n   <\/p><pre>mbuild vigenere.cpp libvigenere.lib<\/pre><p>On UNIX, you link against a <tt>.so<\/tt> file instead of a <tt>.lib<\/tt> file:\r\n   <\/p><pre>mbuild vigenere.cpp libvigenere.so<\/pre><p>In both cases, <tt>mbuild<\/tt> produces an executable called <tt>vigenere<\/tt>.\r\n   <\/p>\r\n   <p>Encrypt the message with the secret key.<\/p><pre>&gt;&gt; !vigenere -e \"Algebra, the Music of the Reason\" \"MATLAB\"\r\n   MLZPBSM LSEAYUKTCA FSDHFLRXLSPZ<\/pre><p>The first argument is the message, the second argument the key. Note the leading exclamation point -- this command runs the\r\n      <tt>vigenere<\/tt> executable from within MATLAB, using the <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/techdoc\/ref\/system.html\"><tt>system<\/tt><\/a> command. You can run these commands on the UNIX or DOS command line as well, but you have to <a href=\"https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/bqrw4o0-1.html\">configure your environment correctly<\/a>.\r\n   <\/p>\r\n   <p>Decrypt to verify the encryption worked:<\/p><pre>&gt;&gt; !vigenere -d \"MLZPBSM LSEAYUKTCA FSDHFLRXLSPZ\" \"MATLAB\"\r\nALGEBRA THE MUSIC OF THE REASON<\/pre><p>Because the alphabets in the Vigenere square only include letters and the space character, the decrypted message lacks punctuation\r\n      marks. Extending the algorithm to handle punctuation is an exercise left to the reader.\r\n   <\/p>\r\n   <p>And extra points if you can figure out why I chose that phrase (aside from its poetic merit, which is in the eye of the beholder).<\/p>\r\n   <h3>Next: Using Multiple Shared Libraries<a name=\"6\"><\/a><\/h3>\r\n   <p>I've shown you how to combine several MATLAB-based functions into a single shared library, and how to incorporate that library\r\n      into a host application. In a later posting, I'll demonstrate how to use multiple shared libraries from a single host application.\r\n   <\/p>\r\n   <p>What else can I tell you about shared libraries? Let me know <a href=\"https:\/\/blogs.mathworks.com\/loren\/?p=264#respond\">here<\/a>.\r\n   <\/p><script language=\"JavaScript\">\r\n<!--\r\n\r\n    function grabCode_396cf332a6d44a6a81dce0cebb54fbba() {\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='396cf332a6d44a6a81dce0cebb54fbba ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 396cf332a6d44a6a81dce0cebb54fbba';\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_396cf332a6d44a6a81dce0cebb54fbba()\"><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.11<br><\/p>\r\n<\/div>\r\n<!--\r\n396cf332a6d44a6a81dce0cebb54fbba ##### SOURCE BEGIN #####\r\n%% Creating C++ Shared Libraries and DLLs\r\n% Guest blogger \r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/authors\/4660 Peter Webb>\r\n% 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%% \r\n% A previous post demonstrated how to use \r\n% <https:\/\/www.mathworks.com\/products\/compiler MATLAB Compiler> to create\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/f7-996249.html \r\n% standalone executables>. In this article, I'll demonstrate how to\r\n% use MATLAB Compiler to create C and C++ \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/f2-995712.html\r\n% shared libraries or DLLs>.\r\n%\r\n% You create a shared library or DLL to add MATLAB-based\r\n% functionality to an application you're developing. You select one or more\r\n% MATLAB-based functions to include in the shared library, and MATLAB\r\n% Compiler generates a binary file that you link against your\r\n% application. Shared libraries generated by MATLAB Compiler are\r\n% compatible with the Microsoft Visual Studio development environment on\r\n% Windows and with the GNU C\/C++ tool suite on most UNIX platforms. The\r\n% list of <https:\/\/www.mathworks.com\/support\/compilers\/current_release\/index.html \r\n% supported compilers> changes from one release to the next; be sure to\r\n% check that list before starting your project.\r\n% \r\n%% Building a Shared Library\r\n% To illustrate the process of creating and using shared libraries, I'll\r\n% use a cryptographic algorithm, the \r\n% <http:\/\/en.wikipedia.org\/wiki\/Vigen%C3%A8re_cipher Vigenere cipher>. The\r\n% program I've written consists of two parts:\r\n%\r\n% * |libvingenere|: A shared library containing two MATLAB functions \r\n% |encrypt| and |decrypt|.\r\n% * |vigenere.cpp|: A C++ main program that calls the functions in\r\n% |libvigenere|.\r\n%\r\n% The \r\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/29443-deploying-a-shared-library \r\n% source code> for the MATLAB functions and the main program is\r\n% available on <https:\/\/www.mathworks.com\/matlabcentral\/ MATLAB Central>.\r\n% The download package also includes\r\n% |VigenereDetails.html|, which describes the implementation of \r\n% the Vigenere cipher in MATLAB. \r\n%\r\n% The  \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/mcc.html\r\n% |mcc|> command invokes MATLAB Compiler both from within interactive \r\n% MATLAB and at the system (DOS or UNIX shell) prompt.\r\n% Use |mcc| to build a shared library from the MATLAB |encrypt| and\r\n% |decrypt| MATLAB functions:\r\n%\r\n%   mcc -v -W cpplib:libvigenere -T link:lib encrypt decrypt\r\n%\r\n% This |mcc| command breaks down into four parts:\r\n%\r\n% * |-v|: Turn on verbose output.\r\n% * |-W cpplib:libvigenere|: Generate C++ wrapper code. Name the generated library |libvigenere|.\r\n% * |-T link:lib|: Invoke a C\/C++ compiler to create a platform-specific \r\n% binary shared library file from the generated code.\r\n% * |encrypt decrypt|: Place the |encrypt| and |decrypt| functions in the\r\n% shared library. Generate C++ wrapper functions for each.\r\n% \r\n% This command generates several files. Two of them are relevant here:\r\n%\r\n% * |libvigenere.dll|: The platform-specific binary: the shared library itself. \r\n% On most Unix systems, this file ends with a |.so| extension: |libvigenere.so|.\r\n% * |libvigenere.h|: Declarations of the C++ wrapper functions and C++ \r\n% type conversion classes and utilities.\r\n%\r\n%% The Generated Interface\r\n% MATLAB Compiler generates many different \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/f2-998954.html \r\n% kinds of functions>: initialization, termination, error and print\r\n% handling and, of course, the  \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/f10-999433.html \r\n% functions you selected> to compile into the library.\r\n%\r\n% In our example, MATLAB Compiler generates a C++ entry point for\r\n% |encrypt| and |decrypt|. Stripped of some bookkeeping annotation, these\r\n% functions look very much like the corresponding MATLAB functions. \r\n% \r\n%  void encrypt(int nargout, mwArray& ciphertext, \r\n%               const mwArray& plaintext, const mwArray& key);\r\n%\r\n%  void decrypt(int nargout, mwArray& plaintext, \r\n%               const mwArray& ciphertext, const mwArray& key);\r\n%\r\n% The generated functions differ from the MATLAB functions in two\r\n% significant ways:\r\n%\r\n% * The C++ functions explicitly declare the types of their arguments.\r\n% * The C++ functions return |void|, passing back results in output\r\n% parameters provided in the argument list.\r\n%\r\n% Let's look at the |encrypt| function in detail. For comparison, here's\r\n% |encrypt|'s MATLAB <http:\/\/en.wikipedia.org\/wiki\/Function_signature \r\n% function signature>:\r\n%\r\n%   function ciphertext = encrypt(plaintext, key)\r\n%\r\n% The |encrypt| MATLAB function has one output and two inputs. The\r\n% |encrypt| C++ function has zero outputs (the |void| return type) and four\r\n% inputs. The first C++ input indicates the number of outputs requested by\r\n% the caller. As indicated by the MATLAB function, the number of outputs\r\n% may be zero or one. Passing any other value will result in an error. The\r\n% second C++ input is the output argument, passed by reference. |encrypt|\r\n% will overwrite any data in this argument with the encrypted message. The\r\n% third and fourth C++ input arguments are the function inputs, the\r\n% plaintext and the encryption key. They are passed by \r\n% <http:\/\/en.wikipedia.org\/wiki\/Const-correctness constant reference> which\r\n% means the |encrypt| function cannot change their contents.\r\n%\r\n% Unlike MATLAB, C++ requires all variables have declared, immutable types.\r\n% Variables in MATLAB have types as well (matrix, cell array, structure, etc.),\r\n% but the type of a MATLAB variable can change at any time. To accommodate\r\n% this dynamic behavior in C++, the MATLAB Compiler provides the \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/f0-98564.html \r\n% |mwArray|> data type. All the functions generated by the MATLAB Compiler\r\n% take |mwArray| inputs and return |mwArray| outputs. The |mwArray| API\r\n% allows you to create |mwArray| objects from most C++ data types and to\r\n% extract native C+++ data from a returned |mwArray|.\r\n% \r\n%% Calling Functions in a Shared Library\r\n% Now that I've created a shared library, I need to write a program to call\r\n% the library's public functions. The program performs six tasks:\r\n%\r\n% # Includes the shared library's header file.\r\n% # Parses command line arguments.\r\n% # <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/mclinitializeapplication.html Initializes> the \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/f12-999353.html MATLAB Compiler Runtime>'s global state and the shared library's state.\r\n% # Creates input arguments; convert native C++ data types to \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/f0-98564.html MATLAB data types>.\r\n% # Invokes one or more functions from the shared library.\r\n% # <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/mclterminateapplication.html Shuts down> the library and the MATLAB Compiler Runtime.\r\n%\r\n% Below, I demonstrate how these steps translate into the code of the\r\n% example's main program, |vigenere.cpp|.\r\n%\r\n% *Step 1*: All programs that use a MATLAB Compiler-generated shared library must include\r\n% the library's header file. The header file has the same base name as the\r\n% compiled library, |libvigenere| in this case, and a |.h| extension.\r\n%  \r\n%  \/\/ vingenere.cpp: Encrypt and decrypt using the Vigenere cipher.\r\n%  #include \"libvigenere.h\"\r\n%  #include <iostream>\r\n%\r\n% *Step 2*: The main program parses the command line. The first argument,\r\n% a switch, determines the type of action: |-e| means encrypt, |-d|\r\n% decrypt. The second argument is the message, and the third, the key.\r\n%\r\n%  int main(int ac, const char *av[])\r\n%  {\r\n%      \/\/ Encrypt or decrypt? Determined by command line switch\r\n%      bool enc = strcmp(av[1], \"-e\") == 0;\r\n%\r\n% *Step 3*: Initialize the runtime and start the library before calling any\r\n% functions exported from the runtime or the library. Failure to initialize\r\n% will cause your program to crash. Always check for success (the\r\n% initializers return |false| if they fail) and issue error messages as\r\n% necessary.\r\n%\r\n%      \/\/ Initialize the MATLAB Compiler Runtime global state\r\n%      if (!mclInitializeApplication(NULL,0)) \r\n%      {\r\n%          std::cerr << \"Could not initialize the application properly.\"\r\n%                    << std::endl;\r\n%          return -1;\r\n%      }\r\n%  \r\n%      \/\/ Initialize the Vigenere library\r\n%      if( !libvigenereInitialize() )\r\n%      {\r\n%          std::cerr << \"Could not initialize the library properly.\"\r\n%                    << std::endl;\r\n%          return -1;\r\n%      }\r\n%\r\n% *Step 4*: Convert the C++ strings from the command line (the message and\r\n% the key) into MATLAB strings by creating mwArray objects. These\r\n% declarations _cannot_ appear before the initialization calls in Step 3.\r\n%\r\n%      \/\/ Must declare all MATLAB data types after initializing the \r\n%      \/\/ application and the library, or their constructors will fail.\r\n%      mwArray text(av[2]);\r\n%      mwArray key(av[3]);\r\n%      mwArray result;\r\n%  \r\n% *Step 5*: Invoke the exported functions. Encrypt or decrypt as indicated\r\n% by the command line switch. Note that the C++ functions have the same\r\n% name as their MATLAB counterparts, and that all return values must be\r\n% passed in by reference. The |mwArray| class defines \r\n%\r\n%      \/\/ Initialization succeeded. Encrypt or decrypt.\r\n%  \r\n%      if (enc == true)\r\n%      {\r\n%          \/\/ Encrypt the plaintext text with the key.\r\n%          \/\/ Request one output, pass in two inputs\r\n%          encrypt(1, result, text, key);\r\n%      }\r\n%      else\r\n%      {\r\n%          \/\/ Decrypt the ciphertext text with the key.\r\n%          \/\/ Request one output, pass in two inputs\r\n%          decrypt(1, result, text, key);\r\n%      }\r\n%      std::cout << result << std::endl;\r\n%\r\n%\r\n% *Step 6*: Shut down the library and the runtime, in the opposite order of\r\n% initialization (library first, then runtime).\r\n%\r\n%      \/\/ Shut down the library and the application global state.\r\n%      libvigenereTerminate();\r\n%      mclTerminateApplication();\r\n%  }\r\n%\r\n%% Creating and Running the Application\r\n% MATLAB Compiler uses the\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/mbuild.html \r\n% |mbuild|> function to compile the code it generates into a shared\r\n% library. |mbuild| knows how to invoke the C\/C++ compiler with the correct\r\n% switches so the compiler can find the required include files and\r\n% libraries. You can use |mbuild| to create your own executables and link\r\n% them with MATLAB Compiler-generated shared libraries. On Windows, for\r\n% example, issue this command:\r\n% \r\n%  mbuild vigenere.cpp libvigenere.lib\r\n%\r\n% On UNIX, you link against a |.so| file instead of a |.lib| file:\r\n%\r\n%  mbuild vigenere.cpp libvigenere.so\r\n%\r\n% In both cases, |mbuild| produces an executable called |vigenere|.\r\n%\r\n% Encrypt the message with the secret key. \r\n%\r\n%  >> !vigenere -e \"Algebra, the Music of the Reason\" \"MATLAB\"\r\n%     MLZPBSM LSEAYUKTCA FSDHFLRXLSPZ\r\n%\r\n% The first argument is the message,\r\n% the second argument the key. Note the leading exclamation point REPLACE_WITH_DASH_DASH this\r\n% command runs the |vigenere| executable from within MATLAB, using the \r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/techdoc\/ref\/system.html\r\n% |system|> command. You can run these commands on the UNIX or DOS command\r\n% line as well, but you have to\r\n% <https:\/\/www.mathworks.com\/help\/releases\/R2010b\/toolbox\/compiler\/bqrw4o0-1.html \r\n% configure your environment correctly>.\r\n% \r\n% Decrypt to verify the encryption worked:\r\n%\r\n%  >> !vigenere -d \"MLZPBSM LSEAYUKTCA FSDHFLRXLSPZ\" \"MATLAB\"\r\n%  ALGEBRA THE MUSIC OF THE REASON\r\n%\r\n% Because the alphabets in the Vigenere square only include letters and the\r\n% space character, the decrypted message lacks punctuation marks. Extending\r\n% the algorithm to handle punctuation is an exercise left to the reader. \r\n%\r\n% And extra points if you can figure out why I chose that phrase (aside\r\n% from its poetic merit, which is in the eye of the beholder).\r\n\r\n%% Next: Using Multiple Shared Libraries \r\n% I've shown you how to combine several MATLAB-based functions into a \r\n% single shared library, and how to incorporate that library into a host\r\n% application. In a later posting, I'll demonstrate how to use multiple\r\n% shared libraries from a single host application. \r\n% \r\n% What else can I tell you about shared libraries? Let me know\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=264#respond here>.\r\n\r\n##### SOURCE END ##### 396cf332a6d44a6a81dce0cebb54fbba\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\/02\/03\/creating-c-shared-libraries-and-dlls\/\">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\/264"}],"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=264"}],"version-history":[{"count":1,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/264\/revisions"}],"predecessor-version":[{"id":2274,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/264\/revisions\/2274"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=264"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=264"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=264"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}