从Matlab调用类时出现分段错误 [英] Segmentation fault when calling class from matlab
问题描述
我在以下代码中遇到了分段错误,我真的不知道这里发生了什么.看来这与Master类中的指针有关,但是我不确定如何解决这个问题.我有以下代码:
I am getting a segmentation fault with the following code, and I really dont know what is happening here. It seems that it has something to do with the pointer in the Master-class, but I am not sure how to solve this. I have the following code:
class Shape
{
public:
Shape(){}
~Shape(){}
virtual void draw() = 0;
};
class Circle : public Shape
{
public:
Circle(){}
~Circle(){}
void draw()
{
printf("circle");
// code for drawing circle
}
};
class Line : public Shape
{
public:
Line() {}
~Line() {}
void draw()
{
printf("line");
// code for drawing line
}
};
class Master
{
public:
Shape* member_shape;
public:
Master()
{}
~Master()
{}
void add_shape_circle()
{
member_shape = new Circle();
}
void add_shape_line()
{
member_shape = new Line();
}
};
Master* master_object;
您是否有办法使此代码正常工作?谢谢.
Do you have any clue how to get this code working? Thanks.
编辑(添加了主要功能):
EDIT (added main function):
实际上,在我的代码中没有像下面这样的主函数,因为我在MATLAB c-mex函数中使用该代码.但它看起来应该像这样:
Actually there exists no main-function like the following in my code, because I am using the code in a MATLAB c-mex function. But it should look like this:
//... classes from above here
int main()
{
master_object = new Master();
master_object->add_shape_circle();
master_object->member_shape->draw(); // segmentation error here
return 0;
}
- 编辑
如果我在Master
构造函数中直接将Circle
对象实例化,则不会发生该错误.但是,就没有办法在Line
和Circle
之间进行选择.示例:如果将Master
类更改为以下内容,则函数调用master_object->member_shape->draw()
不会导致错误.
The error does not occur if I instatiate the Circle
object dircetly in the Master
-constructor. But then there is no way to choose between Line
and Circle
. Example: If I change my Master
class to the following, then the function call master_object->member_shape->draw()
does not lead to an error.
class Master
{
public:
Shape* member_shape;
public:
Master()
{
member_shape = new Circle();
}
~Master()
{}
void add_shape_circle(){}
void add_shape_line(){}
};
所以,这个未初始化的指针有问题……我想.
So, there is something up with this uninitialized pointer...I think.
推荐答案
问题可能与您使用printf
有关.来自 https://www.mathworks.com/help/matlab/matlab_external/creating-c-mex-files.html?requestedDomain=www.mathworks.com :
The issue might be related to your using printf
. From https://www.mathworks.com/help/matlab/matlab_external/creating-c-mex-files.html?requestedDomain=www.mathworks.com :
使用cout或C语言printf函数无法按预期在C ++ MEX文件中工作.请使用mexPrintf函数.
Using cout or the C-language printf function does not work as expected in C++ MEX files. Use the mexPrintf function instead.
这篇关于从Matlab调用类时出现分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!