VC++中調用MATLAB *.m函數編譯後的動態連結程式庫

來源:互聯網
上載者:User

      作為MATLAB的初學者,我最近在看如何?MATLAB與VC的混合編程,查了不少資料,也借鑒了網上很多的寶貴經驗和建議,現我把這份集合大家集體智慧的過程寫下來,供大家參考,以希望能和高手多多交流。

 

      軟體版本:MATLAB 7.0  VC 6.0

 

      1. 進行MATLAB C/C++編譯器的設定

 

>>mbuild -setup
Please choose your compiler for building standalone MATLAB applications:
Would you like mbuild to locate installed compilers [y]/n?
Select a compiler:
[1] Lcc C version 2.4 in D:/MATLAB7/sys/lcc
[2] Microsoft Visual C/C++ version 6.0 in C:/Program Files/Microsoft Visual Studio
[0] None
Compiler: 2
Please verify your choices:
Compiler: Microsoft Visual C/C++ 6.0
Location: C:/Program Files/Microsoft Visual Studio
Are these correct?([y]/n): y
Try to update options file: C:/Users/peng/Application Data/MathWorks/MATLAB/R14/compopts.bat
From template:             

D:/MATLAB7/BIN/WIN32/mbuildopts/msvc60compp.bat  
Done . . . 
--> "D:/MATLAB7/bin/win32/mwregsvr D:/MATLAB7/bin/win32/mwcomutil.dll"
DllRegisterServer in D:/MATLAB7/bin/win32/mwcomutil.dll succeeded
--> "D:/MATLAB7/bin/win32/mwregsvr D:/MATLAB7/bin/win32/mwcommgr.dll"
DllRegisterServer in D:/MATLAB7/bin/win32/mwcommgr.dll succeeded

[注意]:我之前沒有設定成功是由於我的VC裝在了D盤中,後來把VC重裝了一遍,放在C盤就可以了

 

2.  編寫MATLAB的*.m檔案

     比如:

function y =E1(x)
y=x.*x-2*x+x.*x.*x;
plot(x,y);

 

3.  將*.m檔案編譯成VC可以調用的DLL

     >>mcc -W libhg:<自己定義的庫檔案名稱字,如E1DLL> -T link:lib E1(m檔案的名字).m

     完成上面的命令就產生了一系列檔案,其中有用的是:E1DLL.lib,E1DLL.h E1DLL.dll,E1DLL.crf,將上述檔案拷到當前VC的工作目錄下。

 

4. 設定VC的環境

 

  •  Tool->Options->directories裡:include files 要添加<matlab>/EXTERN/INCLUDE  <MATLAB>/EXTERN/INCLUDE/CPP;
    library files要增加<MATLAB>/EXTERN/LIB/WIN32/MICROSOFT/MSVC60 。
  • project->setting->links中: object/library modules中添加mclmcrrt.lib和本工程的中的lib檔案:E1DLL.lib。
  •  

    5.   在VC中調用DLL

         幾個關鍵函數:

         //初始化: 

    res=E1DLLInitialize();
     if(!res)
     {
      MessageBox("初始化Lib錯誤!");
     }

     

    //解構函式

    E1DLLTerminate();

     

    //調用計算

    double x =0.4;  //定義一個變數
     mxArray *t;     //定義輸入函數
     mxArray *y;    //定義輸出函數
     y=NULL;
     t=mxCreateDoubleMatrix(1,1,mxREAL);
     memcpy(mxGetPr(t),&x,sizeof(double));
     mlfE1(1,&y,t);  

    //計算的核心函數,“1”表示函數有輸出,在E1DLL.h中間中,是自動產生的介面

     mclWaitForFiguresToDie(NULL);//等待圖形視窗關閉
     mxDestroyArray(t);
     mxDestroyArray(y);

    [注意]:不要忘了#include “E1DLL.h”

    以上就是我進行的主要過程。

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.