AbstractThis article introduces the features of VC ++ and MATLAB, discusses three methods of programming the MATLAB and VC ++ interfaces, and discusses in detail the methods and implementation processes of programming the MCC and COM component interfaces. The research shows that using the VC ++ and Matlab programming methods reduces the programming difficulty and gives full play to their respective advantages.KeywordsMATLAB; VC ++; MCC; com; Interface ProgrammingMATLAB is a scientific computing software developed by Mathworks. It integrates high-performance numerical computing, symbol computing, and visualization, it also provides a large number of built-in functions and a rich toolbox for easy use and high programming efficiency. However, Matlab is an explanatory language with low operating efficiency and is not suitable as a general programming platform.VC ++ is a visual integrated development environment launched by Microsoft Based on the Windows platform. It has powerful functions in terms of running speed, functionality, and application interface development, however, VC ++ does not have many advantages in numerical calculation and drawing. Therefore, using MATLAB for core program development, using VC ++ to make a friendly program interface, and then combining the two can greatly improve programming efficiency. 1 Overview of VC ++ and Matlab interface methods 1.1 Matlab Engine Methods The Matlab Engine uses client/server (Client/Server) to provide a set of matab API functions. By calling these functions, the Matlab Engine can transmit data between program processes. In application, the VC ++ program is used as the front-end client. It transmits commands and data to the Matlab Engine and receives data information from the Matlab Engine for dynamic communication.1.2 MATLAB Compiler (MCC) MCC is an optimized compiler in MATLAB. With MCC, you can convert the MATLAB Math Library, graphics library, and interface MATLAB program into an EXE application independent of MATLAB and a DLL dynamic Connection Library, write the program interface in VC and load and call the dynamic connection library to connect the two.1.3 COM components The Component Object Model (MCR) is an object model with components as the release unit. It provides an industrial standard that can share binary code and allow access by any program that complies with the standard. Therefore, it is very convenient to develop com as a collaboration between different languages. The com compiler of MATLAB is a new tool that was provided in Matlab 6.5. This product was renamed as MATLAB builder for com since MATLAB 7.0. The com-based hybrid programming method is also recommended by Mathworks.Among the above three methods, the Matlab Engine is used, the overall performance of the application is good, and the Matlab Engine supports comprehensive functions, but the MATLAB background operation is required and cannot be separated from the malab environment. Both the MCC method and the COM component method can be separated from the MATLAB environment, and the application program running efficiency is high, which is conducive to software development. This article will focus on the MCC and COM component methods. [I can see in the book that another method is to generate a DLL program that can be called by MATLAB in VC: a dedicated interface function (int Nlhs, mxarray * plhs [], int nrhs, const mxarray * prhs []), method] [Preliminary Study on MEX (The content from the netizen blog http://hi.baidu.com/wangyantsing/blog/item/c1cecfbf1333a20918d81f2f.html Thanks) Enter the following code in the built-in editor of MATLAB and save it as fact. C, which is stored in the system working directory. # Include "Mex. H" Void mexfunction ( Int nlhs, mxarray * plhs [], Int nrhs, const mxarray * prhs [] ) { Double N, J, * P; Int I;
N = mxgetscalar (prhs [0]); Plhs [0] = mxcreatedoublematrix (1, 1, mxreal ); P = mxgetpr (plhs [0]); J = 1.0; For (I = N; I> 1; I --) J = J * I; * P = J; } This is just a simple example of factorial. Then, I entered> Mex fact. C in MATLAB.
If there is no error, everything will be normal. Then, I enter > Y = fact (5) Will output y = 120 ] [We can see MATCOM on the Internet again today] [MATCOM Conversion Method MATCOM is an integrated development environment developed by Mathworks for efficient interpretation and debugging of m Files in MATLAB. Compile the M file in MATCOM. First, translate the M file into the CPP source code according to its correspondence with the CPP library in MATCOM, and then compile the CPP file into the corresponding EXE or DLL file using the C compiler. Using MATCOM, the generated code is readable, supports graphical functions, and supports file nesting during M file compilation, which can be separated from the MATLAB environment; the defect is that the M file to be compiled cannot involve the internal class of Matlab. MATCOM Conversion Method
The following uses MATLAB 6.5, MATCOM 4.5, VC ++ 6.0, and Windows XP as examples. MATLAB includes mathematical functions and Toolbox functions. MATCOM has compiled general mathematical functions and can be directly used in VC ++ following the MATCOM language rules. toolbox functions must be used, compile the M file of MATLAB under MATCOM. 1.
Figure 1 MATCOM Conversion Method |
1. Use Only MATLAB mathematical functions Add the System File v1_1v. dll and the file matlib. h and v1_1.lib in the system file in windows to the VC ++ project directory, and then include the file matlib. h and the linked file v1_1.lib in the program. After the installation of matcom, the refguide.pdf file is automatically generated on the installation terminal. the functions listed in the file can be directly used in VC ++. 2. Use MATLAB mathematical functions and Toolbox Functions After completing the above steps, you can use MATCOM to convert the M file of the required function to a CPP file or DLL file and add it to the VC ++ project for use. MATCOM is easy to use, so we will not detail the conversion process here. In particular, if M files are nested during the conversion process, all M files should be in the same directory. The following example describes the application of MATCOM in engineering development by calling the MATLAB random function, noise function, and digital modulation and reconciliation function in the communication toolbox under VC ++. (1) Use MATCOM to convert the m Files of Random Functions randint, Noise Function AWGN, digital modulation function dmod, and demodulation function ddemod in MATLAB to VC ++'s H files and CPP files. (2) establish a VC ++ project and add the required documents to the project. (3) follow the MATCOM format and use random functions to generate random binary sequences. After digital modulation, noise is added, and then the digital demodulation function is used to extract binary sequences. Figure 2 interface when the VC ++ program is running (after monochrome processing ):
Figure 2 VC ++ simulation program running interface |
Conclusion Using MATCOM to implement mixed programming of MATLAB and VC ++ is an effective way to develop data processing applications. The main advantages of this method are as follows: (1) provides a large number of mature functions in MATLAB. (2) give full play to the powerful data visualization functions of Matlab. (3) Take advantage of the Windows platform with powerful development tool VC ++. (4) The program can be separated from the MATLAB runtime environment. To sum up, the MATCOM conversion method maximizes the use of the features of the above software and combines difficult Algorithm Research with practical applications, the program is concise, the programming efficiency is improved, and the algorithm is easier to implement. During the development process, researchers with existing programming experience can quickly solve the problem by calling functions as long as they are familiar with function calls and syntax formats of MATLAB, instead of spending a lot of time and effort researching specific algorithms, you can focus more on professional research. ] 2 MATLAB Compiler (MCC) 2.1 MATLAB and VC ++ Interface Configuration To use the MCC method, you must set the MATLAB and VC ++ interfaces. The configuration steps are as follows:1) MATLAB compiler ConfigurationFirst, enter the mbuild-setup command in the MATLAB command prompt and select the compiler. (Note that a certain version of VC ++ must be installed on the computer, this article selects visual c ++ 6.0) to complete compiler settings.2) VC ++ Environment Settings(1) set the path of the header file and library file. In the VC ++ environment menu bar, choose tools> Options> directories. In the "show directories for" column, select include files, in "directories", add <php7.0 installation project> \ extern \ Lib \ Win32 \ Microsoft \ msvc ++ 60. Select librarys files in the "show directories for" column again, and then add the "<MATLAB installation directory> \ extern \ include" in "directories.(2) set the compilation connection options. In the VC ++ environment menu bar, select project-> setting, select the link tab, and add mclmcrrt in the modules bar of Object/library. lib libtest. LIB; select the General tab, and select use MFC in a shared library in the Microsoft Foundation Classes column.2.2 instance demonstration After you complete the MATLAB and VC ++ interface settings, You can implement MATLAB and VC ++ interface programming. The specific steps are as follows:1) Compile the m function file "mypascal. m"Function M = mypascal (N)M = Pascal (N );M = M ';The example m function file generates an N-level Pascal matrix and returns it. Pascal matrix features: the elements in the first row and the first column are 1, the elements at other locations are the sum of the elements at the front and above. Note: In Matlab, the matrix storage method is to take the matrix column first, that is, the data is stored from the first column to the column one by one, in C/C ++, the matrix is gradually stored as the first line. Therefore, the transpose operation is performed on the return matrix in the last line of the function, this is equivalent to storing the computed matrix data in row mode.2) Compile m FilesEnter MCC-B csharedlib: libtest mypascal In the MATLAB command line. m-V command (or MCC-W Lib: libtest-T link: Lib mypascal. m) Compile m Files into C Shared dynamic link library files. After the command is executed, the C header file (libtest. h). Import the database file (libtest. lib), CTF (libtest. CTF) file, dynamic link library file (libtest. DLL), C source file (libtest. c.3) create a project dialog box Run visual c ++ to create a dialog box project named test. All default settings are accepted. Remove the static text and buttons in the dialog box, add a button, a static text box, an edit box, and a list control. Right-click list control, select properties, and change view to report, dialog Box 1 is displayed. Add the clistctrl Class Object m_list to the List Control, associate the edit box with an integer member variable m_size, and add a message response function to the button. Figure 14) Add the compilation file to the ProjectCompile the "libtest. h "," libtest. DLL, libtest. lib "," libtest. copy the four CTF files to the project directory and run libtest. h. Add the project and in the program file testdlg. add the header file "libtest. H ".5) Call the dynamic Connection Library in VC ++① Add libtest initialization in the oninitdialog () function. DLL Process Code: bool ctestdlg: oninitdialog () {cdialog: oninitdialog (); // todo: add extra initialization here if (! Mclinitializeapplication (null, 0) {afxmessagebox ("the program cannot be initialized! "); Exit (1) ;}if (! Libtestinitialize () {afxmessagebox ("The Connection Library cannot be initialized! "); Exit (1);} return true; // return true unless you set the focus to a control}② Add the following code to the void ctestdlg: oncreatebuttom () function to call mypascal. M and display the calculation result in the dialog box. Void ctestdlg: oncreatebuttom () {// todo: add your control notification handler code hereupdatedata (true); double data; data = double (m_size); mxarray * size; // input parameter mxarray * out = NULL; // output parameter // create an mxarray data object with Double Precision scalar size = mxcreatedoublescalar (data); // assign values for memory ReplicationMemcpy (mxgetpr (size), & Data, 1 * sizeof (double )); Mlfmypascal (1, & out, size); // function call [the first parameter indicates the number of output parameters. Here is one] // Display result data Cstring strtext; int I, j; // clear the displayed data m_list.deleteallitems (); intncolumn = m_list.getheaderctrl ()-> getitemcount (); for (I = 0; I <ncolumn; I ++) m_list.deletecolumn (0); // set the title bar m_list.insertcolumn (0, ""); // The Null Value m_list.setcolumnwidth ); // set the width of each column for (I = 0; I <m_size; I ++) {strtext. format ("column % d", I + 1); m_list.insertcolumn (I + 1, strtext); m_list.setcolumnwidth (I + 1, 60 );} // display the result data for (I = 0; I <m_size; I ++) {strtext. format ("row % d", I + 1); m_list.insertitem (I + 1, strtext); For (j = 0; j <m_size; j ++) {strtext. format ("%. F ", * (mxgetpr (out) + I * m_size + J); m_list.setitemtext (I, j + 1, strtext) ;}} mxdestroyarray (size ); // data memory released mxdestroyarray (out );}③ Use classwizard to add the ondestroy () function in the dialog box and add the following code: void ctestdlg: ondestroy () {cdialog: ondestroy (); // todo: add your message handler code her libtestterminate (); // terminate the mclterminateapplication () process; // terminate MCR}Compile and run result 2 in VC ++, which is the same as running m Files in MATLAB.Figure 2 6) Independent Application release When releasing an independent application, you need to copy the following files to the target machine: mcrinstaller.exe, which is located in the <php7.0 installation directory> \ tool-box \ compiler \ deploy \ plugin), shared library (. DLL) and its corresponding CTF file can be copied to the target computer for independent operation.3 COM component 3.1 create COM component in MATLAB To use the COM component method, you must first create a COM component in MATLAB. The steps are as follows:1) create COM componentsIn the MATLAB command window, enter the command comtool to open the MATLAB builder dialog box, which is the main working environment of MATLAB builder for com. Click file-> new project. A new Project Setting dialog box is displayed. Enter the component name and class name. Click OK to create a new project. If the directory of the selected project does not exist, comtool prompts that the directory does not exist and asks whether to create the directory. If yes is selected, comtool creates the project to this directory.2) Add M files to componentsAfter completing the first step, return to the MATLAB builder interface. Click the project you just created and click Add files to add the M file to the new component class. Click build-> COM object to compile the COM component of the current project. This step not only compiles the COM component, but also registers the component on the computer, it can be used in VC ++ like other COM components. After compilation, two sub-folders SRC and distrib will be generated under the project directory set by the user. SRC contains the source code of the component, and distrib contains the COM component for the final release of the user.3) package components and MCRThe COM component generated after compilation can only be used on the current computer. In order to publish it to other computers for use, other support files are required. In addition, unlike common DLL files, COM components must be registered before they can be used on computers. Select the component-> package component command. comtool packs all the files required to publish the component into an executable file with the same name as the project. You can choose whether to include MCR in the package. The COM component generated by MATLAB must run in the MCR environment. If MCR is not installed on the target computer, it is best to include MCR when packaging components so that the package file contains the MCR Installation File. After the package is completed, the executable file of cmd.exe in distribwill be displayed. This is a self-extracting compressed file. It contains four files: _install.bat, DLL, CTF, and mcrinstaller.exe. Copy the local .exe file to the computer on which you want to publish it. And register the component file in the system.3.2 instance demonstration Here we still use the "mypascal. m" file in the above example. Follow the steps described in section 3.1 to create the COM component. The component name is tpascal and the class name is tpascalclass. Run visual c ++ to create a dialog box project that is the same as the preceding example, and set the dialog box as the preceding example. Then, perform the following operations in the MFC project:1) import the DLL fileCopy tpascal_00000.dll from the distrib folder to the project folder, and use the VC ++ command # import to import tpascal_00000.dll to the project, # The import command is used to import the interface type definition in the component from tpascal_00000.dll. The specific method is in stdafx. h, add the following two lines: # import "tpascal_00000.dll" raw_interfaces_onlyusing namespace tpascal;2) add implementation code for the project dialog boxIn the dialog box, click the message response function to compile the code of the calling component: void ctestdlg: oncreatebutton () {// todo: add your control notification handler code hereupdatedata (true); coinitialize (null ); // initialize com // obtain the CLSID of the COM object; hresult hr; HR = clsidfromprogid (olestr ("tpascal. tpascalclass.1 _ 0 "), & CLSID); // create a COM object instance itpascalclass * pipascal; HR = cocreateinstance (CLSID, null, clsctx_inproc _ server, __uuidof (itpascalclass ), (lpvoid *) & pipascal); If (fail Ed (HR) // test whether the creation is successful {afxmessagebox ("create failed"); Return ;}// initialize the variant variable variant size, out; variantinit (& size ); variantinit (& out); // create a size, type: vt_r8, that is, double size. vt = vt_r8; size. dblval = (double) m_size; // create a two-dimensional array out. The type is vt_array, and the elements in the array are double-type out. vt = vt_array | vt_r8; safearraybound bound [2]; // you can specify the number of elements in the First-dimensional array and bound [0] under the element index. celements = m_size; bound [0]. llbound = 0; // set the number of elements in the second-dimensional array and the bound lower bound to the element index [1]. celements = m_size; bound [1]. Llbound = 0; out. parray = safearraycreate (vt_r8, 2, bound); pipascal-> mypascal (1, & out, size); // function call // return value to pass double * matrix, * pdest; matrix = new double [m_size * m_size]; safearrayaccessdata (Out. parray, (void **) & pdest); // obtain the Data Pointer and access the data memcpy (matrix, pdest, m_size * sizeof (double )); // copy the data matrix safearrayunaccessdata (Out. parray); // release the Data Pointer and cancel access to safearraydestroy (Out. parray); // release the array // The code displayed for the result data is the same as that shown in the previous example ...... Delete [] matrix; // release pointer pipascal-> release (); If (pipascal! = NULL) {pipascal = NULL;} variantclear (& size); // clear the variable variantclear (& out); couninitialize (); // release com}. The compilation and running results in VC ++ are the same as those in the previous example, and are consistent with the results of running m Files in MATLAB.3) independent program releaseAnd register tpascal_00000.dll. Copy the executable file .exe of the mfcproject to the target computer and run it to release the independent program.4 Conclusion In the process of software development, in order to improve the efficiency of software development, interface programming is a common method that combines the advantages of multiple development tools. This paper adopts the C ++ and Matlab programming methods based on MCC and COM components, which has the advantages of simplicity, high execution efficiency, almost all MATLAB functions, and ease of transplantation, it is an effective way to solve matrix processing, computing, and image processing programming. It can provide stronger technical support for scientific research and engineering technologies. All the code in this article is in Windows XP, Matlab 7.0.1 and VC ++ 6.0 are all debugged.References [1] su Jinming. MATLAB advanced programming [M]. Beijing: Electronics |