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;
}

样例

猜你喜欢

转载自blog.csdn.net/m0_37772174/article/details/81711980