这几天在用Matlab引擎,发现一个问题:动态数组不能正确传递进去,在Google上找了会,明确回答这个问题的人并不多,好在今天偶尔发现答案,归根到底是自己C语言基础太差了!
主要在于对sizeof函数理解有误:对于常规数组a,sizeof(a)返回的就是数组所占的字节数;对于动态数组,无论是new还是calloc,返回的都是一个指针pr,而sizeof(pr)返回只是类型的字节数,由此导致数组变量传不到matlab引擎中。图和代码如下:
#include "stdafx.h"
#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include <vector>
#include "iostream"
#include "engine.h"
using namespace std;
#pragma once
#define BUFSIZE 1024
int _tmain(int argc, char ** argv)
{
int SampleNum=100;
double TimeSpan=15.0f; //15秒
double * Time=new double[SampleNum];
for (int i=0;i<SampleNum;i++)
{
Time[i]=TimeSpan/SampleNum*i;
}
cout<<"Size of Variable 'Time' is : "<<sizeof(Time)<<endl; //对动态数组sizeof只能返回对应类型(int、double)的大小
Engine * ep;
if (!(ep=engOpen("")))
{
cout<<"Cannot open the matlab engine!"<<endl;
getchar();
}
char Buffer[BUFSIZE];
mxArray * mpTime=NULL;
mpTime=mxCreateDoubleMatrix(1,SampleNum,mxREAL);
//memcpy((void *)mxGetPr(mpTime),(void *)Time,sizeof(Time)); //这样写是错误的!
memcpy((void *)mxGetPr(mpTime),(void *)Time,sizeof(double)*SampleNum);
engEvalString(ep,"clc;close all;clear all");
engPutVariable(ep,"t",mpTime);
Buffer[BUFSIZE-1]='\0';
engOutputBuffer(ep,Buffer,BUFSIZE); //显示Command Window输出
engEvalString(ep,"t(1:10)");
printf("%s",Buffer);
engEvalString(ep,"T=sin(t)+0.1*randn(1,length(t));");
engEvalString(ep,"plot(t,T,'b');hold on;plot(t,sin(t),'r');title('Example');xlabel('Time');ylabel('T');grid on");
mxDestroyArray(mpTime);
engClose(ep);
getchar();
//return 0;
}