C/C++和matlab混合編程

有些時候使用混合編程能夠讓程序更加高效

筆者所使用的matlab軟件爲2018a,C++編譯器爲Microsoft Visual C++ 2017(matlab本身是不帶C/C++編譯器的,安裝編譯軟件是必須的)

仍然是先從簡單的hello world 開始

首先編寫一個C++程序(當然也可以C程序)


#include <iostream>
#include<mex.h>
using namespace std;

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
	cout << "Hello world" << endl;
}

命名爲hw.cpp

將hw.cpp複製到matlab的工作路徑下,在命令行窗口輸入mex hw.cpp並回車,之後會在工作路徑下生成hw.mexw64文件

輸入hw則執行hw.mexw64文件

接着編寫一個能夠在matlab中調用C++程序,用於計算當前是一年當中的第幾天

接口函數mexFunction必須包括的參數有

參數名稱 參數描述
prhs 輸入參數
plhs 輸出參數
nrhs 輸入參數的個數
nlhs 輸出參數的個數
#include <iostream>
#include "mex.h"    //頭文件必須包含mex.h 

using namespace std;
double c_n(int year, int month, int day);
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	double *y;
	int year, month,day;
	//獲取輸入變量的數值大小  
	year = (int)mxGetScalar(prhs[0]);
	month = (int)mxGetScalar(prhs[1]);
	day = (int)mxGetScalar(prhs[2]);
	//獲取輸出變量的指針  
	plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);//創建一個輸出矩陣
	y = mxGetPr(plhs[0]);
	//調用子函數  
	*y=c_n( year, month,day);
	if ((month < 1) || (month > 12)) {
		printf("月份數據輸入錯誤,強制輸出爲0\n");
		*y = 0;
	}
	if ((day < 1) || (day > 31)) {
		printf("日號數據輸入錯誤,強制輸出爲0\n");
		*y = 0;
	}
}
   
double c_n( int year,int month,int day)
{
	int flag = 0;
	if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 100))flag = 1;
	else flag = 0;
	int a = 0;
	switch (month - 1)
	{
	case 11:a += 30;
	case 10:a += 31;
	case 9:a += 30;
	case 8:a += 31;
	case 7:a += 31;
	case 6:a += 30;
	case 5:a += 31;
	case 4:a += 30;
	case 3:a += 31;
	case 2:a += 28 + flag;
	case 1:a += 31; break;
	default:;
	}
	a += day;
	double tyr;
	tyr = (double)a;
	return tyr;
}

樣例

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章