我正在使用GNU GCC编译器(在Windows上)开发Code :: Blocks上的C ++项目。
该项目由5个文件组成,并使用Code :: Blocks完美运行。但是,当我尝试从Matlab运行可执行文件(在debug
目录中找到)时,它会直接崩溃。从我的观点来看,这是因为Matlab中没有很好地识别内存分配(xx = new struct [int])。
据观察,如果删除包含分配的行(new struct
和new vec
),则可以从Matlab运行可执行文件。 (结构和向量的大小必须在int main()
)
这是代码:基本上,它初始化几个向量(嵌入在结构中),每个向量的维度为(x,y,z)* nbrcompon。
(请不要告诉我有关使用#include <vector>
)
Main.cpp的
#define EASYDYNMBSMAIN
#include <iostream>
#include "Vectors.h"
using namespace std;
int main()
{
nbrvec=3;
nbrcompon=2;
cout << "Hello world!" << endl;
InitVec();
cout << VectorArray[2].velocity[0] << endl; // must be commented to run from Matlab
return 0;
}
Vectors.cpp
#include "Vectors.h"
void InitVec()
{
if (nbrvec>0)
{
VectorArray=new structvectors[nbrvec]; // must be commented to run from Matlab
for(int ivec=0; ivec< nbrvec; ivec++ )
{
VectorArray[ivec].velocity= new vec[nbrcompon]; // must be commented to run from Matlab
}
VectorArray[2].velocity[0].put(2.03,3.2,36.2); // must be commented to run from Matlab
}
}
Vectors.h
#ifndef VECTORS_H_INCLUDED
#define VECTORS_H_INCLUDED
#include <iostream>
#include <iomanip>
#include <math.h>
#include <stdlib.h>
using namespace std;
#include "Components.h"
struct structvectors
{
vec *velocity;
};
#ifdef EASYDYNMBSMAIN
#define EASYDYNSIMMAIN
structvectors *VectorArray=0;
int nbrvec=0;
int nbrcompon=0;
#else
extern structvectors *VectorArray;
extern int nbrvec;
extern int nbrcompon;
#endif
void InitVec();
#endif // VECTORS_H_INCLUDED
Components.cpp
#include <math.h>
#include "Components.h"
vec::vec(double xinit, double yinit, double zinit)
{
x=xinit; y=yinit; z=zinit;
}
void vec::put(double xcoord, double ycoord, double zcoord)
{
x=xcoord; y=ycoord; z=zcoord;
}
ostream &operator<<(ostream &stream, vec v)
{
stream << setw(15) << v.x << " " << setw(15) << v.y
<< setw(15) << v.z;
return stream;
}
istream &operator>>(istream &stream, vec &v)
{
stream >> v.x >> v.y >> v.z;
return stream;
}
Components.h
#ifndef COMPONENTS_H_INCLUDED
#define COMPONENTS_H_INCLUDED
#include <iostream>
#include <iomanip>
#include <math.h>
#include <stdlib.h>
using namespace std;
// Definition of vector components
class vec
{
public :
double x,y,z;
vec(double xinit=0.0, double yinit=0.0, double zinit=0.0);
void put(double xcoord, double ycoord , double zcoord);
friend ostream &operator<<(ostream &stream, vec v);
friend istream &operator>>(istream &stream, vec &v);
};
#endif // COMPONENTS_H_INCLUDED
运行可执行文件的简单Matlab代码
clear all
close all
clc
system('VecProject.exe &')
有任何解决问题的建议吗?
提前感谢您的回答; - )