Mixed programming interface and application __linux of MATLAB and C + +

Source: Internet
Author: User
Tags function definition prepare response code win32

Original link: http://www.cnblogs.com/lidabo/archive/2012/08/24/2654148.html

Original link: http://blog.csdn.net/jtop0/article/details/7657227

Matlab mixed programming interface and its application with C + +

Absrtact: Matlab has a strong numerical calculation and analysis capabilities, and C/S is the most popular advanced programming language, both complementary combination of mixed programming in scientific research and engineering practice has a very important significance. From Matlab to invoke C/C + + code and call M file, the paper deeply studies the principle and implementation mechanism of mixed programming between them, and gives the mixed programming method and steps under the specific conditions. The experiment shows that the MATLAB and C/S mixed programming interface and its application method are effective and practical.

  1 Introduction

MATLAB is currently the most widely used mathematical software, has a strong numerical calculation, data analysis and processing, system analysis, graphic display and even symbolic operations such as the function [1]. Using this complete mathematical platform, users can quickly realize very complex functions and greatly improve the efficiency of engineering analysis and calculation [2][3]. But compared with other advanced programs [3], the MATLAB program is a kind of interpretation execution program, without compiling and so on preprocessing, the program runs slower [4].

C/s + + language is one of the most popular advanced programming languages [5]. It can operate the operating system and the application and the hardware directly, use C/C + + language is obviously superior to other advanced interpretation of high-level language, some large application software such as Matlab is developed in the language.

In the engineering practice, users often encounter the problem of mixed programming between MATLAB and C + +. Based on the development environment of MATLAB 6.5 and VC6.0, this paper makes an in-depth study on the mixed programming problem between them under Windows platform and gives examples.

  2 matlab to call C + +

There are two main ways for Matlab to call C + +: Using MEX technology and calling C + + Dynamic Connection library.

In the MATLAB and C + + mixed programming, you must first compile the MATLAB application Mex and compiler mbuild the correct settings [1]:

to MATLAB compile application Mex settings: Mex–setup.

On the MATLAB compiler mbuild settings: Mbuild–setup.

  2.1 Calling MEX files for C/A + +

MEX is the abbreviation of MATLAB executable, it is a kind of "can call in MATLAB of C (or FORTRAN) language derivative program" [6]. The use of MEX file is extremely convenient, and its calling mode is exactly the same as the built-in function of MATLAB, just type the MEX filename at the MATLAB command prompt.

The MEX source of a C/s + + program usually consists of 4 components, the first 3 of which must be included, and the 4th is flexibly selected according to the functions implemented: (1) #include "mex.h";(2) the entry function of MEX file Mexfunction, Mex file export name must be Mexfunction function; (3) Mxarray; (4) API function

A simple example illustrates the process of writing and invoking the MEX source program for C + +:

#include "mex.h"
void  timestwo (double y[], double x[])
{ 
     y[0] = 2.0*x[0];
void  mexfunction (int  nlhs,  Mxarray * plhs[], int nrhs,  const Mxarray *prhs[])
{
    double *x,* y; 
    int  mrows, ncols;
if (nrhs!=1) 
           mexerrmsgtxt ("one input required.");

else if (nlhs>1) 
           mexerrmsgtxt ("Too manyoutput arguments");
Mrows = Mxgetm (Prhs[0]); 
    Ncols = MXGETN (Prhs[0]);
if (!mxisdouble (prhs[0)) | | | Mxiscomplex (PRHS[0) | |! (mrows ==1 && ncols==1))
         mexerrmsgtxt ("Input must Be a Noncomplex scalar double. ");     Plhs[0] = Mxcreatedoublematrix (  mrows,  ncols,  mxreal);     x = MXGETPR (prhs[0]);    
         y = MXGETPR (plhs[0]);  
         Timestwo (y,x); 
 }    


can be compiled in MATLAB, can also be compiled directly in the C + + environment:

1). ( in matlab ) with instructions Mex TIMESTWO.C compile this file, and then in the MATLAB command line down with the generated MEX file. 2. ( in VC2008 ) as compiled with General C + +, the DLL will be generated, which can be used directly in MATLAB, or copy and change the suffix name. Mexw32. (because Matlab r2010b later version may not support calling DLL as suffix Mex file)

  2.2 Call + + Dynamic Connection library (ie: ordinary C program DLL does not use MEX interface function)

MATLAB provides interfaces to DLL files for dynamically connected libraries [7]. Using this interface, we can call the function exported by Dynamic Connection library in MATLAB. Matlab's interface to DLL supports DLL files written in various languages. Before calling the DLL file, you need to prepare the header file for the function definition. For DLL files developed in the C + + language, you can use the corresponding header files in the source program, and for DLLs developed in other languages, you will manually prepare the equivalent C language function definition header file.

The use of Dynamic Connection library interface technology in MATLAB usually requires the following 4 steps to complete:

(1) Open the Dynamic Connection library file, (2) Prepare the data for the calling function, (3) invoke the function exported in the Dynamic Connection library file, and (4) Close the Dynamic connection library file.

In order to achieve the above steps, the use of MATLAB functions are: LoadLibrary, LoadLibrary, Calllib, Libfunctions, Lipointer, Libstruct, libisloaded. The following example illustrates the method and procedure for MATLAB to call the C + + Dynamic Connection library:

A. In VC environment, the new project->win32 dynamic link library-> project name test1->empty Project-> completed;

B. Create a new->c++ source file-> add A.cpp, which reads:#include "a.h"

  _declspec (dllexport) int Add (int a, int b) {return a+b;}

C. New->c/c++ header file-> add a.h, content is: _declspec (dllexport) int Add (int a,intb); Then compile and generate Test1.dll Dynamic Connection library file, will Test1.dll and a.h copy to the MATLAB working directory.

D. Under the MATLAB command line, call Test.dll:>>loadlibrary (' Test1 ', ' a.h '); >>x=7;

>>y=8;  >>calllib (' Test1 ', ' Add ', x,y); Ans=15 >>unloadlibrary (' Test1 ').

The method of invoking DLL dynamic Connection library provides a simple and convenient method for reusing a large number of practical C + + code accumulated in engineering practice of MATLAB. This method is more convenient and practical than the call Mex file. But this interface support C, does not support C + + library and function overload, in this case, recommend using Mex-file, if you really want to use this method ( call C + + Dynamic Connection library ), then for C + + to make some changes, see http:// Www.mathworks.de/help/techdoc/matlab_external/f43202.html#bq__4nu-1,

  3/C + + call Matlab

In the engineering practice, the method of Matlab is called by the MATLAB calculation engine, the C + + file containing M file conversion, and the DLL file generated by the call M file.

  3.1 calculation engine using MATLAB

MATLAB Engine Library provides users with some interface functions, using these interface functions, users in their own programs in the calculation of the engine way to invoke MATLAB files. This method uses a client/server approach, using the MATLAB engine to connect matlab with C + +. In the practical application, C + + program for the client, MATLAB as the local server.

C + + program to MATLAB calculation engine to pass command and data information, and from the MATLAB computing engine to receive data information [2].

MATLAB provides the following several C language computing engine access functions for users to use [8]:engopen,engclose, Enggetvariable,engputvariable,engevalstring, Engoutputbuffer,engopensingleuse, Enggetvisible,engsetvisible.

The following is written in C language, call the MATLAB engine calculation equation x3 2x+5=0 Root source program example2.c as an example, explain C + + calls MATLAB Computing engine programming principle and steps:

#include <windows.h> #include <stdlib.h> #include <stdio.h> #include "engine.h" int PASCAL Winmai N (HANDLE hinstance, HANDLE hprevinstance, LPSTR lpszcmdline, int n  
Cmdshow) {Engine *ep;   <pre name= "code" class= "CPP" > Mxarray *p=null,*r=null;<pre name= "code" class= "CPP" > Char buffer[301];
Double Poly[4] = {1,0,-2,5}; <pre name= "code" class= "CPP" > if (!  EP =engopen (NULL)) {<pre name= "code" class= "CPP" > fprintf (stderr, "\ncan ' t-start MATLAB engine\n");
     return exit_failure;  &NBSP} P = Mxcreatedoublematrix (1, 4, mxreal);
     Mxsetclassname (P, "P");
     memcpy ((char *) MXGETPR (P), (char *) poly, 4*sizeof (double));  Engputvariable (EP, P);
     Engoutputbuffer (EP, buffer, 300);
     Engevalstring (EP, "Disp" ([' Polynomial ', poly2str (p, ' x '), ' root ']), R=roots (P) ");
     MESSageBox (Null,buffer, "example2 show the application of MATLAB engine", MB_OK); Engclose (EP);  
     Mxdestroyarray (P);

return exit_success; }

Under the MATLAB run Example2.exe:mex-f example2.c. The results of the run are as shown in Figure 1:

Using the calculation engine to invoke MATLAB is characterized by: save a lot of system resources, the overall performance of the application is better, but can not be separated from the environment of MATLAB operation, and running slower, but in some special applications [9] (such as the need for three-dimensional graphics display) can be considered.

3.2 cpp and HPP files generated by MCC compilers

The c++complier--MCCwith MATLAB can convert m file to C + + code. As a result, it provides another convenient way to invoke the M file for C + + programs. The following example illustrates the appropriate steps:

A. New example3.m:function Y=exmaple3 (n) y=0;  For I=1:n Y=y+i; End

After saving, enter in the command window: MCC-T-L cpp-h example3.

The Example3.cpp and example3.hpp two files are generated in the working directory.

B. In VC create a Dialog based MFC application Test2, add a button, and add a button response function, function content see F step. Copy the two files generated above to the TEST2 directory of VC project.

C. Select in VC: Project-> settings, select the property sheet link option, select Input from the Drop-down menu, add LIBMmfile.lib libmatlb.lib to the object/library module Libmx.lib libmat.lib libmatpm.lib sgl.lib libmwsglm.lib libmwservices.lib, (after three for the use of MATLAB graphics library, you need to add) pay attention to separate space, and in the Ignore library to add msvcrt.lib;

D. Select the property sheet C + + option, the Drop-down menu selects General, retains the original content in the preprocessor definition, and adds Msvc,ibmpc,mswind, separated by commas. Select the precompiled Headers option for the Drop-down menu, add the stdafx.h in the auto use pre-compensation header, and then determine.

E. Selection: Tool-> option, property page Select "Directory", add in Include Files: C:\MATLAB6p5p1\extern\include, C:\MATLAB6p5p1\extern\include\cpp; Library files Add: C:\MATLAB6p5p1\bin\win32, C:\MATLAB6p5p1\extern\ lib\win32\microsoft\msvc60; Note According to the user's MATLAB installation location, Modify the corresponding directory.

F. Add header file in response function: #include "matlab.hpp" #include "example3.hpp" function response code is:

int i;  Mwarray N;  n=10;  N=example3 (n); I=n.extractscalar (1);

CString str; Str.  Format ("Example3 return value is:%d", I); AfxMessageBox (str);

G. Compile, connect, execute, and the results are shown in Figure 2.

3.3 DLL files generated by MCC compilers

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.