您的位置:首页 > 编程语言 > MATLAB

matlab与C/C++混合编译

2013-11-27 14:54 260 查看
好多学习Matlab扩展编程的人经常把这几个命令给搞混淆的,下面我就给大家仔细讲讲,希望呢给大家讲明白!

先简单的说说mcc、mbuild和mex到底怎么回事:

mcc将M文件转换成C/C++文件和相应的MEX包裹文件(需要Matlab编辑器),但在特定条件下可以自动调用mbuild或者mex

mex将C/C++文件(入口函数为mexfunction())编译成MEX(DLL)文件(需要C/C++编辑器)

mbuild将C/C++文件(入口函数为main())生成可独立运行的C应用程序(需要C/C++编辑器)

复制代码
一 mcc命令

Matlab编译器使用mcc命令能将一个M文件翻译成C文件,同时生成一个相应的包裹文件,这个包裹文件包含了编译器产生的代码和它支持的可执行文件类型之间所需的接口。利用改包裹文件提供的接口,生成的C文件能用在任何编译器所支持的可执行文件类型(如MEX文件、EXE文件、DLL文件)中,这些C文件与最终生成的可执行文件是相互独立的。

Matlab编译器(Lcc)在特定的条件下能自动调用mex和mbuild函数,尤其是mcc –x/-m/-p时。

(1)创建MEX文件

>>mcc –x filename (注意这个命令在2008a中已经去掉了)将M文件filename.m翻译成C代码,并生成一个可被Matlab直接调用的C的MEX。

(2)创建simulink S函数

>>mcc –s filename

将M文件filename.m翻译成C代码,并生成一个相应的simulink S函数,该函数的输入输出变量的大小可动态改变。

(3)创建可独立执行的C程序

>>mcc –m filename

将M文件filename.m翻译成C代码,生成的可执行文件能独立于Matlab运行环境。

(4)创建可独立运行的C++程序

>>mcc –p filename

将M文件filename.m翻译成C++代码,生成的可执行文件能独立于Matlab运行环境。

(5)创建可独立运行的C图形库函数

>>mcc –B sgl filename

如果filename.m中包含了对Matlab图形处理函数的调用,上述命令,将filename转换成为C语言,并生成一个能独立于Matlab运行环境的可执行程序。

(6) 创建可独立运行的C++图形库函数

>>mcc –B sgl cpp filename

如果filename.m中包含了对Matlab图形处理函数的调用,上述命令,将filename转换成为C++语言,并生成一个能独立于Matlab运行环境的可执行程序。

(7)创建C函数库

>>mcc –m –W lib:libfoo –T link:libfoo.m

创建一个C函数库

二 mex命令

用户可以在Matlab中按简单的M文件语法规则设计出来完成特定计算的算法。然后用Matlab编译器调用mex命令创建C共享库函数(DLL)或C++静态函数库,最后将它们整合到C/C++应用程序中,编译完这些C/C++应用程序,就可以用这些算法来实现特定的计算功能。当然这过程中也隐藏了算法和加快了代码的执行效率。

由于MEX文件执行效率高,故如果有文件重名的话,Matlab将优先调用MEX文件,下面以一个例子说明:

function theimage=gasket(numpoits)

theimage=zeros(1000);

corners=[866 1;1 500;866 1000];

startpoit=[866 1];

therand=ceil(rand(numpoits,1)*3);

for ii=1:numpoits

startpoit=floor((corners(therand(ii),:)+startpoit)/2);

theimage(startpoit(1),startpoit(2))=1;

end

imagesc(theimage)

colormap([1 1 1;0 0 0]);

axis equal tight

复制代码
现在直接调用

>> tic ,gasket(5000000);toc

Elapsed time is 7.240129 seconds.

复制代码
接着把它编译成mex文件在调用试试

>>mcc -p tic gasket;tic ,gasket(5000000);toc

Elapsed time is 1.23861 seconds.

复制代码

三 mbuild命令

要建立独立运行的C应用程序,系统中需要安装Matlab、Matlab编译器、C/C++编译器以及Matlab C/C++数学库函数和图形库函数。

Matlab编译器使用mbuild命令可以直接将C/C++源代码编译为独立运行程序,在这些源代码中可以使用Matlab提供的接口来调用Matlab数学库函数。

虽然生成的可执行程序可以脱离Matlab环境运行,但是它需要Matlab C/C++数学库文件或者图形库文件的支持才能运行。但如果C/C++源代码完全是按传统C/C++源代码语法规则编写,没有包含Matlab数学库和图形库的调用,则不仅可以独立与Matlab环境,也不需要那两个库函数的支持。

对于如何在其他环境中运行那个生成的exe文件,大家看看这个帖子:http://www.matlabsky.com/thread-543-1-1.html

下面说说一些比较和区别:

1. MEX文件和EXE文件的差别

Mex文件与Matlab解释器在同一个过程空间运行,当用户调用一个MEX文件时Matlab解释器就会动态的连接到MEX文件。

可独立运行的C/C++应用程序(exe)可以独立于Matlab环境而运行,而MEX文件则不行,它需要Matlab的支持。还有EXE中可以调用MEX文件。

2.mex和mbuild编译的C/C++文件的差别

使用mbuild命令编译的C/C++源文件中,必须包含main()函数,它能独立于Matlab运行。而mex命令编译的C/C++源文件中不含main()函数,它是以mexfunction()函数作为入口的,编译后生成的是mex文件,被Matlab调用。

下面是我的一些使用心得

由于真正掌握C/C++接口编程比较麻烦,故对初学者较少直接使用mex命令(花费那么大的精力去学习那些接**术,接着利用接**术编写C/C++文件,再使用mex命令来编译它),一般大家都是先写好M文件再使用mcc
–x命令让它生成MEX (DLL)文件。但对纯正的C/C++大家却都比较熟悉,故mbuild命令还是有些市场的。

使用MATLAB的MCC命令生成C/C++程序

先,配置MATLAB

用如下命令:

mex –setup

mbuild -setup

例一:将m文件转化成库文件使用

1、建立一个名为ceshidll.m的M函数文件,该函数的功能是输入两组数完成两组数据的插值拟合,并将结果用图形表示:

ceshidll.m文件内容如下:

function ceshidll(x,y)

a=min(x):0.1:max(x);

b = interp1(x,y,a,''spline'');%一维插值函数

plot(x,y,''*'',a,b);

2、在MATLAB Command中用如下命令编译函数ceshidll.m:

>> mcc -t -W libhg:dlltest -T link:lib -h libmmfile.mlib ceshidll.m

参数说明:

-t 将m文件编译为C\C++代码

-W libhg:dlltest 生成使用C函数图形库的文件,生成的文件名为dlltest

-T link:lib 生成库文件

-h 辅助选项,可以将任何被调用的辅助函数都包含到编译的文件中

libmmfile.mlib连接任何需要的共享函数库

ceshidll.m 被编译的文件名

编译完成后在MATLAB当前目录下会生成以下文件: ceshidll.c、ceshidll.h 、dlltest.c 、dlltest.exports、dlltest.h、dlltest.mlib、dlltest.exp、dlltest.lib、dlltest.dll。其中dlltest.h 、dlltest.lib和dlltest.dll文件是我们需要的。

使用方法:

#include "matlab.h"

#include "dlltest.h"

#pragma comment(lib,"dlltest")

关键代码:

UpdateData(TRUE);  //刷新输入数据

double X[100],Y[100];

CString AA,BB,a;

int i=1;

mxArray *A=NULL;  //初始化矩阵

mxArray *B=NULL;

  AA=m_edit1;  //字符串赋值

  BB=m_edit2;

.....//将字符转化为数字

mlfEnterNewContext(0, 0); //自动管理内存

dlltestInitialize();

mlfCeshidll(A,B);  //调用dll文件中函数

mxDestroyArray(A);  //释放矩阵内存

mxDestroyArray(B);

mlfRestorePreviousContext(0, 0);

例二:将m文件 转换成对应的C\C++文件

1、在MATLAB中编写如下函数:
function [x]=gjfcz(A,b)

%A=[-1.5 1 2; 4 2 3 ; -3 2 8]

%b=[3;5;6]

x=A\b
保存名为gjfcz.m,该函数的功能为求解线形方程组,可参考第四章的内容。

2、在MATLAB的命令窗口输入以下命令:
mcc –m gjfcz.m


该命令用来生成对应的C文件和可执行程序。在MATLAB工作目录下(一般是MATLAB\work)将会生成如下文件:gjfcz.exe,gjfcz.c,gjfcz.h,gjfcz_main.c,其中gjfcz.c,gjfcz.h是我们需要的文件。

3、新建名为JXXFC基于对话框的工程,面板上添加一个按扭。

4、拷贝gjfcz.c,gjfcz.h两文件到工程目录下,并将文件引入工程(Project->Add to Project->Files)。

5、为按扭添加如下响应代码:

void CJXXFCDlg::OnButton1()

{

  static  double Adata[]={-1.5,4,-3,1,2,2,2,3,8};

  static  double bdata[]={3,5,6};

  double  Xdata[100];

  mxArray *A = NULL;//赋初值

  mxArray *b = NULL;

  mxArray *x = NULL;

  /* 使用自动内存管理*/

   mlfEnterNewContext(0, 0);

  //创建矩阵

  mlfAssign(&A, mlfDoubleMatrix(3, 3, Adata, NULL));

  mlfAssign(&b, mlfDoubleMatrix(3, 1, bdata, NULL));

  InitializeModule_gjfcz();

  x=mlfGjfcz(A,b);//调用gjfcz.c中的函数求解

  TerminateModule_gjfcz();

  memcpy(Xdata,mxGetPr(x),3*sizeof(double));  // mxGetPr(x)用来得到x的地址,从而获得matlab输出

  CString R;

  R.Format("%f\n%f\n%f",Xdata[0],Xdata[1],Xdata[2]);

  MessageBox(R);

  /* 释放矩阵所占的内存*/

  mxDestroyArray(A);

  mxDestroyArray(b);

  mxDestroyArray(x);

  /* 禁用自动内存管理*/

  mlfRestorePreviousContext(0, 0);

}


例三:利用图形库画图

写一个简单的m函数:

function y=huatu_test()

x=-10:0.1:10;

y=sin(x);

plot(x,y,''*'')


文件保存为huatu_test.m。

mcc -t -W libhg:dlltest -T link:lib -h libmmfile.mlib huatu_test.m

#include "dlltest.h"

打开dlltest.h文件,里面有有关函数的定义,找到其中三个函数:

extern mxArray * mlfHuatu_test(void);

extern void dlltestInitialize(void);

extern void dlltestTerminate(void);


从函数意思不难知道它们的作用,dlltestInitialize用来初始化dll库,dlltestTerminate用来结束调用dll,mlfHuatu_test为主程序执行函数。将三个函数拷贝到button响应代码中,进行修改:

void CCeshiDlg::OnButton1()

{

dlltestInitialize();

mlfHuatu_test();

dlltestTerminate();

}


利用mcc命令,通过不同的参数设置可以生成不同的文件,例如:

mcc -B sgl myfun 将myfun.m文件生成对应的c文件和使用c图形库的可执行程序

mcc -B sglcpp myfun 将myfun.m文件生成相应的c++文件和使用c++图形库的可执行程序
mcc的参数实际上有很多,例如:

mcc -t -W main -L C -T link:exe -h libmmfile.mlib myfun


该命令是将myfun.m生成可执行c程序

为了简化选项设置,编译器提供了宏选项,实际上上述命令利用一个参数就可以了:

mcc -m myfun


该命令和上述命令是等价的,也是用来生成可执行c程序。关于mcc命令详细参数设置可以参考MATLAB帮助文档。

大家在使用VC调用MATLAB中遇到什么问题,可以发电子邮件到c_dinco@sina.com,把遇到的问题说清楚,正在写书,同时有什么好的建议,也欢迎发邮件来。

关于程序运行的说明:

1、根据实际情况修改VC中头文件和库文件的路径;

2、如果自己编写的程序图形不能显示菜单栏和工具栏,拷贝文件夹bin到当前目录下

MCC MATLAB to C/C++ Compiler (Version 3.0).

MCC [-options] fun [fun2 ...] [mexfile1 ...] [mlibfile1 ...]

Translate fun.m to fun.c or fun.cpp, and optionally create any supported

binary file. Write any resulting files into the current directory, by

default.

If more than one M-file is specified, a C or C++ file is generated for each

M-file.

If C or object files are specified, they are passed to MEX or MBUILD along

with any generated C files.

If MEX-files are specified, MCC will generate wrapper code so that calls can

be made from compiled M-files to the specified MEX-files. Also, if a

MEX-file and an M-file with the same base name are located in the same

directory, specifying the MEX-file causes MCC to use it instead of the

M-file. Otherwise MCC favors M-files over MEX-files.

MLIB files describe the functions in a shared library created by MCC (see -W

lib below). Specifying an MLIB file tells MCC to link to the MLIB file's

corresponding shared library whenever it needs to use any of the functions

found in that library. The MLIB file and its corresponding shared library

file must be located within the same directory.

If conflicting options are presented to MCC, the rightmost conflicting

option is used.

OPTIONS:

A <option> Specify annotation. The following table shows valid <option>

strings and their effects:

annotation:all (*) - All lines from source M-file appear as comments

in generated output file.

annotation:comments - Comments from source M-file appear as comments in

generated output file.

annotation:none - No text from source M-file appears in generated

output file.

line:on - #line directives appear in generated output file

which map lines in source M-code to lines in

output file.

line:off (*) - No such #line directives are generated.

debugline:on - Run-time error messages report the source file

name and line number where they occurred.

debugline:off (*) - Run-time error messages do not report any

information about the source where they occurred.

(*) indicates default setting.

b Generate an MS Excel compatible formula function for the given list of M-files.

B <filename>[:<arg>[,<arg>]] Specify bundle file. <filename> is a text file containing

Compiler command line options. The Compiler behaves as if the "-B

<filename>" were replaced by the contents of the bundle file. Newlines

appearing in these files are allowed and are treated as whitespace.

The MathWorks provides options files for the following:

ccom Used for building a C COM compatible object on Windows

(requires COM Builder)

cexcel Used for building a C MS Excel Compatable COM object on

Windows (requires MATLAB Excel Builder)

csglcom Used for building C COM compatible object on Windows

using the C Graphics Library (requires COM Builder)

csglexcel Used for building a C MS Excel compatible object on Windows

using the C Graphics Library (requires MATLAB Excel Builder)

csglsharedlib

Used for building a C Graphics Library shared library

cppcom Used for building a C++ COM compatible object on Windows

(requires COM Builder)

cppexcel Used for building a C++ MS Excel Compatiable COM object on

Windows (requires MATLAB Excel Builder)

cppsglcom Used for building C++ COM compatible object on Windows

using the Graphics Library (requires COM Builder)

cppsglexcel

Used for building a C++ MS Excel compatible object on Windows

using the Graphics Library (requires MATLAB Excel Builder)

cpplib Used for building a C++ library

csharedlib

Used for building a C shared library

csglsharedlib

Used for building a C Graphics shared library

pcode Used for building MATLAB P-Code files.

sgl Used for building stand-alone C Graphics applications.

sglcpp Used for building stand-alone C++ Graphics Library

applications.

c C only. Translate M-file to C, but do not produce a MEX-file or

stand-alone application. This is equivalent to "-T codegen" as the

rightmost argument on the command line.

d <directory> Output directory. All generated files will be put in

<directory>.

F list. List the <option>s available in the next form of the command,

together with their current values and a short explanation.

F <option>:<number> Typesetting format options. Assign the value <number> to

the formatting option <option>. See "F list" for <option>s.

f <filename> Use the specified options file when calling MEX or

MBUILD. This allows you to use different ANSI compilers. This

option is a direct pass-through to the MEX or MBUILD script. See

"External Interfaces" for more information.

G Debug only. Simply turn debugging on, so debugging symbol

information is included.

g Debug. Include debugging symbol information. This option also

includes the -A debugline:on switch. This will have an impact on

performance of the generated code. If you wish to have debugging

information, but do not want the performance degradation

associated with the debug line information use: -g -A

debugline:off. This option also includes the -O none switch. That

switch causes all Compiler optimizations to be turned off. If you

wish to have some optimizations on, you may specify them after the

debug switch.

h Compile helper functions. All M-functions called will be compiled into the resulting MEX-file or stand-alone application.

i When generating a library include only entry points mentioned on the

command line in the list of exported symbols.

I <path> Include path. Add <path> to the list of paths to search for

M-files. The MATLAB path is automatically included when running from

MATLAB, but NOT when running from DOS or the Unix shell. See "help

mccsavepath".

L <option> Language. Specifies target language. <option> can be "C" for C, "Cpp" for C++, or "P" for MATLAB P-code.

l Line. Generates code that reports file name and line numbers on run-time errors. (Equivalent to -A debugline:on)

m Macro that generates a C stand-alone application. This is equivalent to

the options "-t -W main -L C -h -T link:exe libmmfile.mlib", which can

be found in the file <MATLAB>/toolbox/compiler/bundles/macro_option_m.

Note: the "-h" means that helper functions will be included.

M "<string>" Pass <string> to the MBUILD or MEX script used to build an

executable. If -M is used multiple times, the rightmost occurrence is

used.

o <outputfilename> Output name. Set the name of the final executable output

(MEX or stand-alone application) to <outputfilename>. A suitable,

possibly platform-dependent, extension is added to <outputfilename>

(e.g., ".exe" for PC stand-alone applications, ".mexsol" for Solaris

MEX-files).

O <optimization> Optimization. There are three possibilities:

<optimization class>:[on|off] - Turns the class on or off

For example: -O fold_scalar_mxarrays:on

list - Lists the available optimization classes.

<optimization level> - Uses a bundle file called

opt_bundle_<level> to determine which optimizations are on or off.

For example "-O all" looks for a bundle file called opt_bundle_all

and uses the switches present. The current optimization levels

are "all" and "none". The default is to have all optimizations

on.

p Macro that generates C++ stand-alone application. This is equivalent to

the options "-t -W main -L Cpp -h -T link:exe libmmfile.mlib", which can

be found in the file <MATLAB>/toolbox/compiler/bundles/macro_option_p.

Note: the "-h" means that helper functions will be included.

S Macro that generates Simulink C-MEX S-Function. This is equivalent to

the options "-t -W simulink -L C -T link:mex libmatlbmx.mlib", which can

be found in the file <MATLAB>/toolbox/compiler/bundles/macro_option_S.

Note: the absence of "-h" means that helper functions will not be

included.

t Translate M code to target language. Translate any M-functions specified on the command line to C or C++ functions. This option is included in all macro options. Omitting it allows the generation of wrapper C/C++ files without generating the C/C++ files corresponding
to M-files.

T <option> Specify target phase and type. The following table shows valid <option> strings and their effects:

codegen - translate M-files to C/C++ files and generate a

wrapper file. (This is the default -T setting.)

compile:mex - same as codegen, plus compile C/C++ files to object

form suitable for linking into a Simulink

S-function MEX-file.

compile:mexlibrary - same as codegen, plus compile C/C++ files to object form suitable for linking into an ordinary (non-S-function) MEX-file.

compile:exe - same as codegen, plus compile C/C++ files to object form suitable for linking into a stand-alone executable.

compile:lib - same as codegen, plus compile C/C++ files to object form suitable for linking into a shared library/DLL.

link:mex - same as compile:mex, plus link object files into a Simulink S-function MEX-file.

link:mexlibrary - same as compile:mexlibrary, plus link object files into an ordinary (non S-function) MEX-file.

link:exe - same as compile:exe, plus link object files into a stand-alone executable.

link:lib - same as compile:lib, plus link object files into a shared library/DLL.

u <number> Specify that the number of inputs to a generated Simulink

S-function should be <number>. Valid only if either "-S" or "-W

simulink" option has also been specified.

v Verbose. Show compilation steps.

w list. List the <msg> strings allowed in the next form of the command,

together with the full text of the warning messages to which they

correspond.

w <option>[:<msg>] Warnings. The possible options are "enable", "disable",

and "error". If "enable:<msg>" or "disable:<msg>" is specified, enable

or disable the warning associated with <msg>. If "error:<msg>" is

specified, enable the warning associated with <msg> and treat any

instances of that warning as an error. If the <option> but not ":<msg>"

is specified, the Compiler applies the action to all warning

messages. For backward compatibility with previous Compiler revisions,

"-w" (with no option) is the same as "-w enable".

W <option> Wrapper functions. Specify which type of wrapper file should be generated by the Compiler. <option> can be one of "mex",

"main", "simulink", "lib:<string>","com:<component-name>,<class-name>,<version>", or "none"(default). For the lib wrapper, <string> contains the name of the shared library to build. When generating a "lib" wrapper, MCC also creates an MLIB file describing the
functions in the shared library.

x Macro that generates a MEX-file. This is equivalent to the options "-t -W mex -L C -T link:mexlibrary libmatlbmx.mlib", which can be found in the file <MATLAB>/toolbox/compiler/bundles/macro_option_x. Note: the absence of "-h" means that helper functions
will not be included.

y <number> Specify that the number of outputs from a generated Simulink

S-function should be <number>. Valid only if either "-S" or

"-W simulink" option has also been specified.

Y <license.dat file> Override default license.dat file with specified

argument.

z <path> Specify the path to use for library and include files.

This option uses the specified path for the Compiler libraries

instead of MATLABROOT.

? Help. Display this help message.

EXAMPLES:

Make a C translation and a MEX-file for myfun.m:

mcc -x myfun

Make a C translation and a stand-alone executable for myfun.m:

mcc -m myfun

Make a C++ translation and a stand-alone executable for myfun.m:

mcc -p myfun

Make a C translation and a Simulink S-function for myfun.m

(using dynamically sized inputs and outputs):

mcc -S myfun

Make a C translation and a Simulink S-function for myfun.m

(explicitly calling for one input and two outputs):

mcc -S -u 1 -y 2 myfun

Make a C translation and stand-alone executable for myfun.m. Look for

myfun.m in the directory /files/source, and put the resulting C files and

executable in the directory /files/target:

mcc -m -I /files/source -d /files/target myfun

Make a C translation and a MEX-file for myfun.m. Also translate and include

all M-functions called directly or indirectly by myfun.m. Incorporate the

full text of the original M-files into their corresponding C files as C

comments:

mcc -x -h -A annotation:all myfun

Make a generic C translation of myfun.m:

mcc -t -L C myfun

Make a generic C++ translation of myfun.m:

mcc -t -L Cpp myfun

Make a C MEX wrapper file from myfun1.m and myfun2.m:

mcc -W mex -L C libmatlbmx.mlib myfun1 myfun2

Make a C translation and a stand-alone executable from myfun1.m and myfun2.m

(using one mcc call):

mcc -m myfun1 myfun2

Make a C translation and a stand-alone executable from myfun1.m and myfun2.m

(by generating each output file with a separate MCC call). Note that the

MLIB file "libmmfile.mlib" only needs to be specified when generating a

wrapper file, and when linking the final executable:

mcc -t -L C myfun1 % yields myfun1.c

mcc -t -L C myfun2 % yields myfun2.c

mcc -W main -L C myfun1 myfun2 libmmfile.mlib % yields myfun1_main.c

mcc -T compile:exe myfun1.c % yields myfun1.o

mcc -T compile:exe myfun2.c % yields myfun2.o

mcc -T compile:exe myfun1_main.c % yields myfun1_main.o

mcc -T link:exe myfun1.o myfun2.o myfun1_main.o libmmfile.mlib

Make a shared/dynamically linked library called "liba" from a0.m and a1.m,

where neither a0 nor a1 calls functions in libmmfile:

mcc -t -W lib:liba -T link:lib a0 a1

Make a shared/dynamically linked library called "liba" from a0.m and

a1.m, where at least one of a0 or a1 calls at least one function in

libmmfile. Define LIBMMFILE to be 1 when compiling the C code.:

mcc -t -W lib:liba -T link:lib a0 a1 libmmfile.mlib -M "-DLIBMMFILE=1"

Make a C translation and a stand-alone graphics library executable from

myfun.m (using one MCC call):

mcc -B sgl myfun1

Make a C++ translation and a stand-alone graphics library executable from

myfun.m (using one MCC call):

mcc -B sglcpp myfun1

Make a shared/dynamically linked library called "liba" from a0.m and a1.m

that makes calls into the MATLAB C/C++ Graphics Library:

mcc -B sgl -t -W libsgl:liba -T link:lib a0 a1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: