300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > 【转】Linux下c++调用自己编写的matlab函数:通过mcc动态链接库.so实现

【转】Linux下c++调用自己编写的matlab函数:通过mcc动态链接库.so实现

时间:2022-08-01 07:31:40

相关推荐

【转】Linux下c++调用自己编写的matlab函数:通过mcc动态链接库.so实现

转自:Linux下c++调用自己编写的matlab函数:通过mcc动态链接库.so实现_Jaster_wisdom的专栏-CSDN博客

之前在这里和这里调用了matlab自带的一些函数,是通过matlab引擎来实现的。那里调用的是matlab自带的函数,那么如果想调用自己写的.m函数该怎么办呢?其实很简单,原理类似,方法也不止一种。这篇笔记我先尝试通过mcc将.m函数编译成动态链接库供c++调用的方式。在另一篇笔记中还尝试了另一种途径:通过matlab引擎来实现。其实,调用自己编写的m函数,只是多了一步将自己的matlab函数编译成动态链接库文件(也就类似自带的那种eigen.h和libeng.so)。这里练习了一个小例子,展示从c++中调用matlab里面的自己写的函数。

实验平台:ubuntu 12.04 + g++4.6 + matlaba

问题描述:

有一个c++程序main.cpp,和一个matlab函数myFunc.m。现在要做这件事:

1)从main.cpp中传递2个double类型的数值a和b到myFunc.m中

2)myFunc.m中求和(sum = a+b)

3)main.cpp中接收myFunc.m返回的和并输出。

思路:

1)设置matlab的编译器,使用gcc编译器。编译m文件成.so。

2)编译.cpp文件,编译时调用.so库(添加.so的路径到编译选项)。

步骤:

1)将自己的matlab函数(myFunc.m)编译成动态链接库

(1)设定编译器为gcc,在matlab 命令行依次执行命令mex -setup和mbuild -setup:

[html]view plaincopy

>>mex-setupOptionsfilescontrolwhichcompilertouse,thecompilerandlinkcommandoptions,andtheruntimelibrariestolinkagainst.Usingthe'mex-setup'commandselectsanoptionsfilethatisplacedin~/.matlab/Raandusedbydefaultfor'mex'.Anoptionsfileinthecurrentworkingdirectoryorspecifiedonthecommandlineoverridesthedefaultoptionsfilein~/.matlab/Ra.Tooverridethedefaultoptionsfile,usethe'mex-f'command(see'mex-help'formoreinformation).Theoptionsfilesavailableformexare:1:/opt/MATLAB/Ra/bin/mexopts.sh:TemplateOptionsfileforbuildinggccMEX-files0:ExitwithnochangesEnterthenumberofthecompiler(0-1):1/opt/MATLAB/Ra/bin/mexopts.shisbeingcopiedto~/.matlab/Ra/mexopts.shcp:cannotcreateregularfile`~/.matlab/Ra/mexopts.sh':Permissiondenied**************************************************************************Warning:TheMATLABCandFortranAPIhaschangedtosupportMATLABvariableswithmorethan2^32-1elements.InthenearfutureyouwillberequiredtoupdateyourcodetoutilizethenewAPI.Youcanfindmoreinformationaboutthisat:/help/techdoc/matlab_external/bsflnue-1.htmlBuildingwiththe-largeArrayDimsoptionenablesthenewAPI.**************************************************************************>>mbuild-setupOptionsfilescontrolwhichcompilertouse,thecompilerandlinkcommandoptions,andtheruntimelibrariestolinkagainst.Usingthe'mbuild-setup'commandselectsanoptionsfilethatisplacedin~/.matlab/Raandusedbydefaultfor'mbuild'.Anoptionsfileinthecurrentworkingdirectoryorspecifiedonthecommandlineoverridesthedefaultoptionsfilein~/.matlab/Ra.Tooverridethedefaultoptionsfile,usethe'mbuild-f'command(see'mbuild-help'formoreinformation).Theoptionsfilesavailableformbuildare:1:/opt/MATLAB/Ra/bin/mbuildopts.sh:BuildandlinkwithMATLABCompilergeneratedlibraryviathesystemANSIC/C++compiler0:ExitwithnochangesEnterthenumberofthecompiler(0-1):1/opt/MATLAB/Ra/bin/mbuildopts.shisbeingcopiedto~/.matlab/Ra/mbuildopts.shcp:cannotcreateregularfile`~/.matlab/Ra/mbuildopts.sh':Permissiondenied>>

(2) 在matlab中,编写myFunc.m文件内容如下:

[html]view plaincopy

function[C]=myFunc(A,B)C=A+B;end

(3) 生成myFunc.m的动态链接库(.so)

[html]view plaincopy

>>mcc-Wcpplib:libmyFunc-Tlink:libmyFunc.m-cWarning:MATLABToolboxPathCacheisoutofdateandisnotbeingused.Type'helptoolbox_path_cache'formoreinfo>>

等待数秒,完成。可以看到myFunc.m所在的目录下生成了多个文件:

[html]view plaincopy

$lslibmyFunc.cpplibmyFunc.ctflibmyFunc.exportslibmyFunc.hlibmyFunc.somain.cppmccExcludedFiles.logmyFunc.mreadme.txt

命令解释:其中-W是控制编译之后的封装格式;cpplib是指编译成C++的lib;cpplib冒号后面是指编译的库的名字;-T表示目标,link:lib表示要连接到一个库文件的目标,目标的名字即是.m函数的名字。-c表明需要生成.ctf文件,比如本例如果不加-c就不会生成“libmyFunc.ctf”。

生成的文件中打开“libmyFunc.h”可以看到一行:

extern LIB_libmyFunc_CPP_API void MW_CALL_CONV myFunc(int nargout, mwArray& C, const mwArray& A, const mwArray& B);

这个就是我们的myFunc.c函数待会儿在c++中调用时的接口。有4个参数,第一个是参数个数,第二个是用来接收函数返回值的,后面2个是从c++中传递进来的变量。我们还会用到“libmyFunc.h”中的另外2个函数:libmyFuncInitialize()初始化,和注销libmyFuncTerminate()。

2)编写main.cpp,代码如下:

[cpp]view plaincopy

#include<iostream>#include"mclmcr.h"#include"matrix.h"#include"mclcppclass.h"#include"libmyFunc.h"#include"mclmcrrt.h"usingnamespacestd;intmain(){//initializelib,这里必须做初始化!if(!libmyFuncInitialize()){std::cout<<"CouldnotinitializelibmyFunc!"<<std::endl;return-1;}//用户输入2个数值doublea,b;cout<<"Pleaseinput2numbers<ab>andthenpressenter:"<<endl;cin>>a;cin>>b;doublec;//usedtoreceivetheresult//为变量分配内存空间,maltab只有一种变量,就是矩阵,为了和c++变量接轨,设置成1*1的矩阵mwArraymwA(1,1,mxDOUBLE_CLASS);//1,1表示矩阵的大小,mxDOUBLE_CLASS表示变量的精度mwArraymwB(1,1,mxDOUBLE_CLASS);mwArraymwC(1,1,mxDOUBLE_CLASS);//调用类里面的SetData函数给类赋值mwA.SetData(&a,1);mwB.SetData(&b,1);//调用自己的函数,求和。myFunc(1,mwC,mwA,mwB);c=mwC.Get(1,1);cout<<"Thesumis:"<<c<<endl;//后面是一些终止调用的程序//terminatetheliblibmyFuncTerminate();//terminateMCRmclTerminateApplication();returnEXIT_SUCCESS;}

3)编译main.cpp函数,调用libmyFunc.so

[html]view plaincopy

$g++-omain-I.-I/opt/MATLAB/Ra/extern/include-L.-L/opt/MATLAB/Ra/runtime/glnxa64main.cpp-lmyFunc-lm-lmwmclmcrrt-lmwmclmcr

开始编译时也遇到一些问题,主要是链接库路径问题导致的编译错误,详细错误汇总在另篇笔记里(点此查看)。

编译成功后,需要装一下MCR Installer,步骤点此。

运行结果:

[html]view plaincopy

$./mainWarning:latestversionofmatlabapp-defaultsfilenotfound.ContactyoursystemadministratortohavethisfileinstalledPleaseinput2numbers<ab>andthenpressenter:10100Thesumis:110$./mainWarning:latestversionofmatlabapp-defaultsfilenotfound.ContactyoursystemadministratortohavethisfileinstalledPleaseinput2numbers<ab>andthenpressenter:11Thesumis:2

源代码及编译过程中的所有文件已打包,点击这里可以下载。

参考:

c++调用matlab生成的Dll动态连接库 - OSCHINA - 中文开源技术交流社区

Linux下动态链接库的创建和使用及C调用matlab动态库问题_ylf13的专栏-CSDN博客

浅析将matlab函数编译成dll供Cpp调用的方法 -

matlab:linux环境中将m文件编译成动态链接库 - Mr.Rico - 博客园

matlab练习程序(c/c++调用matlab<dll>) - Dsp Tian - 博客园

科学网—liuzy的个人资料

c++调用matlab生成的Dll动态连接库_郑海波(莫川)的CSDN博客-CSDN博客_c++调用matlab生成的dll

How to call Matlab from C++ code? - Stack Overflow

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。