【转】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 + matlab2012a

问题描述:
有一个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 plain  copy

  1. >> mex -setup  
  2.   
  3.     Options files control which compiler to use, the compiler and link command options, and the runtime libraries to link against.  
  4.   
  5.     Using the 'mex -setup' command selects an options file that is  
  6.     placed in ~/.matlab/R2012a and used by default for 'mex'. An options   
  7.     file in the current working directory or specified on the command line   
  8.     overrides the default options file in ~/.matlab/R2012a.  
  9.    
  10.     To override the default options file, use the 'mex -f' command  
  11.     (see 'mex -help' for more information).  
  12.   
  13. The options files available for mex are:  
  14.   
  15.   1: /opt/MATLAB/R2012a/bin/mexopts.sh :   
  16.       Template Options file for building gcc MEX-files  
  17.    
  18.   
  19.   0: Exit with no changes  
  20.   
  21. Enter the number of the compiler (0-1):  
  22. 1  
  23.   
  24.   
  25. /opt/MATLAB/R2012a/bin/mexopts.sh is being copied to ~/.matlab/R2012a/mexopts.sh  
  26.   
  27. cp: cannot create regular file `~/.matlab/R2012a/mexopts.sh': Permission denied  
  28.   
  29. **************************************************************************  
  30.   Warning: The MATLAB C and Fortran API has changed to support MATLAB   
  31.            variables with more than 2^32-1 elements.  In the near future   
  32.            you will be required to update your code to utilize the new   
  33.            API. You can find more information about this at:   
  34.            http://www.mathworks.com/help/techdoc/matlab_external/bsflnue-1.html  
  35.            Building with the -largeArrayDims option enables the new API.   
  36. **************************************************************************  
  37.   
  38. >> mbuild -setup   
  39.   
  40.     Options files control which compiler to use, the compiler and link command  
  41.     options, and the runtime libraries to link against.  
  42.   
  43.     Using the 'mbuild -setup' command selects an options file that is  
  44.     placed in ~/.matlab/R2012a and used by default for 'mbuild'. An options   
  45.     file in the current working directory or specified on the command line   
  46.     overrides the default options file in ~/.matlab/R2012a.  
  47.    
  48.     To override the default options file, use the 'mbuild -f' command (see 'mbuild -help' for more information).  
  49.   
  50. The options files available for mbuild are:  
  51.   
  52.   1: /opt/MATLAB/R2012a/bin/mbuildopts.sh :   
  53.       Build and link with MATLAB Compiler generated library via the system ANSI C/C++ compiler  
  54.    
  55.   
  56.   0: Exit with no changes  
  57.   
  58. Enter the number of the compiler (0-1):  
  59. 1  
  60.   
  61.   
  62. /opt/MATLAB/R2012a/bin/mbuildopts.sh is being copied to ~/.matlab/R2012a/mbuildopts.sh  
  63.   
  64. cp: cannot create regular file `~/.matlab/R2012a/mbuildopts.sh': Permission denied  
  65. >>  

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

[html]  view plain  copy

  1. function [ C ] = myFunc(A, B)  
  2.   
  3. C = A+B;  
  4.   
  5. end  

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

[html]  view plain  copy

  1. >> mcc -W cpplib:libmyFunc -T link:lib myFunc.m -c  
  2. Warning: MATLAB Toolbox Path Cache is out of date and is not being used.  
  3. Type 'help toolbox_path_cache' for more info   
  4. >>   

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

[html]  view plain  copy

  1. $ ls  
  2. libmyFunc.cpp  libmyFunc.ctf  libmyFunc.exports  libmyFunc.h  libmyFunc.so  main.cpp  mccExcludedFiles.log  myFunc.m  readme.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 plain  copy

  1. #include <iostream>  
  2. #include "mclmcr.h"  
  3. #include "matrix.h"  
  4. #include "mclcppclass.h"  
  5. #include "libmyFunc.h"  
  6. #include "mclmcrrt.h"  
  7.   
  8. using namespace std;  
  9.   
  10. int main() {  
  11.   
  12.     // initialize lib,这里必须做初始化!  
  13.     if( !libmyFuncInitialize())  
  14.     {  
  15.         std::cout << "Could not initialize libmyFunc!" << std::endl;  
  16.         return -1;  
  17.     }  
  18.   
  19.     // 用户输入2个数值  
  20.     double a, b;  
  21.     cout<<"Please input 2 numbers <a b> and then press enter: "<<endl;  
  22.     cin >> a;  
  23.     cin >> b;  
  24.   
  25.     double c; //used to receive the result  
  26.   
  27.     // 为变量分配内存空间, maltab只有一种变量,就是矩阵,为了和c++变量接轨,设置成1*1的矩阵  
  28.     mwArray mwA(1, 1, mxDOUBLE_CLASS); //1,1表示矩阵的大小, mxDOUBLE_CLASS表示变量的精度  
  29.     mwArray mwB(1, 1, mxDOUBLE_CLASS);  
  30.     mwArray mwC(1, 1, mxDOUBLE_CLASS);  
  31.   
  32.     // 调用类里面的SetData函数给类赋值  
  33.     mwA.SetData(&a, 1);  
  34.     mwB.SetData(&b, 1);  
  35.   
  36.     // 调用自己的函数,求和。  
  37.     myFunc(1, mwC, mwA, mwB);  
  38.   
  39.     c = mwC.Get(1, 1);  
  40.   
  41.     cout<<"The sum is: "<<c<<endl;  
  42.   
  43.     // 后面是一些终止调用的程序  
  44.     // terminate the lib  
  45.     libmyFuncTerminate();  
  46.   
  47.     // terminate MCR  
  48.     mclTerminateApplication();  
  49.   
  50.   
  51.     return EXIT_SUCCESS;  
  52. }  


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

[html]  view plain  copy

  1. $ g++ -o main -I. -I/opt/MATLAB/R2012a/extern/include -L. -L/opt/MATLAB/R2012a/runtime/glnxa64 main.cpp -lmyFunc -lm -lmwmclmcrrt -lmwmclmcr  


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

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

运行结果:

[html]  view plain  copy

  1. $ ./main   
  2. Warning: latest version of matlab app-defaults file not found.  
  3. Contact your system administrator to have this file installed  
  4. Please input 2 numbers <a b> and then press enter:   
  5. 10 100  
  6. The sum is: 110  
  7.   
  8. $ ./main   
  9. Warning: latest version of matlab app-defaults file not found.  
  10. Contact your system administrator to have this file installed  
  11. Please input 2 numbers <a b> and then press enter:   
  12. 1 1  
  13. The sum is: 2  

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

参考:

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

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

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

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

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

科学网—liuzy2011的个人资料

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

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

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/435808.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C#连接数据库SQL(2005)

首先来总结一下进行数据库编程的全过程,这里用的是SQL SERVER(1) 建立SqlConnection对象以连接数据库SqlConnection mysqlconnectionnew SqlConnection("Serverlocalhost; databaseyourdatabase;uidsa;pwdsa");(2) 建立SqlCommand对象SqlCommand mysqlcommandmysqlco…

MULTI BIN的wince 5.0,smdk2440下的实现

原本早就要发出来了&#xff0c;但是看到king_sundi网友已经发过一个帖子了&#xff0c;所以犹豫了没有发&#xff0c;相对而言&#xff0c;我这个总结更具有实用性&#xff0c;基本上照着这个步骤来就能成功&#xff0c;我给我几个朋友试过了&#xff0c;他们一开始对这个基本…

【转】gcc/g++ 链接库的编译与链接

转自&#xff1a;gcc/g 链接库的编译与链接_Surge-CSDN博客_g 链接 gcc/g 链接库的编译与链接 surgewonggmail.com Surge_surgewong_CSDN博客 程序编译一般需要经预处理、编译、汇编和链接几个步骤。在实际应用中&#xff0c;有些公共代码需要反复使用&#xff0c;就把这些代…

常用WebServices返回数据的4种方法比较

以前经常在群里听到朋友们说WebServices的性能特别的慢&#xff0c;说的如何如何。说实话&#xff0c;WebServices的确比调用本地数据要慢一些&#xff0c;可是究竟有多慢&#xff0c;真的如朋友们说的那么难以忍受吗&#xff1f;我个人感觉&#xff0c;多半原因在处理的方式上…

让S3c2410里拥有HIVE注册表的 全部步骤

首先&#xff0c;我是花了几天的时间才搞好的&#xff0c;当然我也在网上找了很多资料&#xff0c;可是网上朋友说可行的方法&#xff0c;我试来试去就是不行&#xff0c;这我也不清楚为什么&#xff0c;一开始有说用到BINFS格式的[指NandFlash分区格式]&#xff0c;后来又看到…

【转】vscode下编译告警“undefined reference”?三步教你如何解决

转自&#xff1a;vscode下编译告警“undefined reference”&#xff1f;三步教你如何解决_squall0984的博客-CSDN博客 近些年来&#xff0c;由于VS Studio体积庞大、价格昂贵等原因&#xff0c;越来越多的C/C开发者转投VSCode的怀抱。VSCode有着免费1、开源2、多平台支持、占…

写在S3C2440A平台+winCE5.0+NAND +HIVE注册表的实现

最近一直弄这个注册表的永久保存&#xff0c;在网上看到很多相关的贴子&#xff0c;就像大部分人说的一样&#xff0c;很少有人照着做就可以成功的。 今天总算成功了&#xff0c;总结经验如下&#xff0c;但愿对后来者有所帮助。 首先&#xff0c;要实现注册表的永久保存&…

非常实用的Asp.net常用的51个代码

1.弹出对话框.点击转向指定页面 Code: Response.Write("<script>window.alert(该会员没有提交申请,请重新提交&#xff01;)</script>");Response.Write("<script>window.location http://www.msproject.cn/index.asp</script>");…

【转】VScode tasks.json和launch.json的设置

转自&#xff1a;VScode tasks.json和launch.json的设置 - 知乎 目录 C&#xff08;方法1&#xff1a;不使用VSCode插件&#xff0c;较繁琐&#xff09;C&#xff08;方法2&#xff1a;使用Native Debug插件&#xff09;C&#xff08;方法3&#xff1a;使用C/C Compile Run插…

小处见大问题

如果有以下几种很简单的需求&#xff0c;可是小需要中隐藏着大问题。 给页面添加4个web按钮&#xff0c;点击4个按钮分别实现 &#xff08;1&#xff09;打开一个摸态对话框 &#xff08;2&#xff09;页面在客户端转向 &#xff08;3&#xff09;页面转向并且进行一个服务器端…

巧手定制Windows CE系统

嵌入式系统正在日益广泛的应用于各个方面&#xff0c;嵌入式系统的最大特点在于其精简和实时性。公司近期委派我负责一个新的嵌入式系统项目&#xff0c;因为是小型设备&#xff0c;所以我面临的第一个难题是需要找一个体积少&#xff0c;但非常灵活添加外围接口的嵌入式系统。…

【转】vscode配置C/C++环境

转自&#xff1a;vscode配置C/C环境 - 知乎 VS Code配置作者&#xff1a;谭九鼎 链接&#xff1a;Visual Studio Code 如何编写运行 C、C 程序&#xff1f; - 知乎 有改动。个人按照步骤后&#xff0c;做到复制上三个json那一步&#xff0c;就可以运行了。 我将settings.json…

Boot Loader的启动流程和开发经验总结

Windows CE最大程度继承了桌面版Windows的丰富功能&#xff0c;但是Windows CE并不是一个通用的安装版操作系统。在形形色色的嵌入式设备世界里&#xff0c;一款CE系统通常只会针对某一种硬件平台生成。 一般来说&#xff0c;Windows CE的开发过程可以分为&#xff1a;0AL…

c# 相对路径的一些文献

1.获取和设置当前目录的完全限定路径。string str System.Environment.CurrentDirectory;Result: C:\xxx\xxx2.获取启动了应用程序的可执行文件的路径&#xff0c;不包括可执行文件的名称。string str System. Windows .Forms.Application.StartupPath;Result: C:\xxx\xxx3.获…

【转】dicom网络通讯入门(1)

转自&#xff1a;dicom网络通讯入门&#xff08;1&#xff09; - assassinx - 博客园 如果只看标准就会越看越糊涂&#xff0c;根本原因就是因为dicom抽象得太严重&#xff0c;是“专家”弄的。没办法。 那么到底服务类是什么&#xff1f;sop 又是什么&#xff1f;&#xff0…

三种嵌入式操作系统的分析与比析

1.1 嵌入式系统 嵌入式系统是以嵌入式计算机为技术核心&#xff0c;面向用户、面向产品、面向应用&#xff0c;软硬件可裁减的&#xff0c;适用于对功能、可靠性、成本、体积、功耗等综合性能有严格要求的专用计算机系统。 嵌入式系统应具有的特点是&#xff1a;高可靠性&#…

用WebORB实现flex + .net后台的Remoting

实现flex与后台通信最简单的方式是采用httpServic的方式&#xff0c;或webservice。但这两种方式都是基于文本的传输&#xff0c;传输效率低&#xff0c;采用RemoteObject的方式&#xff0c;传输的内容采用AMF3格式的二进制编码&#xff0c;效率较高&#xff0c;并且能实现远程…

【转】dicom网络通讯入门(2)

转自&#xff1a;dicom网络通讯入门&#xff08;2&#xff09; - assassinx - 博客园 首先我们现一个echo响应测试工具&#xff0c;也就是echo 的scu&#xff0c;不是实现打印作业管理么。同学我告诉你还早着呢。本来标题取的就是《dicomviewer 第二弹 之 实现打印管理》名字多…

基于WINCE6.0下载multiple XIP镜像文件

备注&#xff1a;基于usb下载的方式&#xff0c;MLC nand flash为K9G8G08U 1. Multiple XIP模式的文件说明 Multiple XIP模式下生成的文件有chain.bin、chain.lst、NK.bin、xip.bin和xipkernel.bin&#xff0c;如下图所示&#xff1a; 图1 2. Eboot下载Multiple XI…

Final Michael Scofield

转载于:https://www.cnblogs.com/andrewx/archive/2009/08/16/1547738.html