Coder with classes: Default values and input checking

1 ビュー (過去 30 日間)
Andreas Klotzek
Andreas Klotzek 2021 年 3 月 4 日
Hi
I have a use case where I have a Matlab class that I want to be part of the interface when generating c++ code. The class holds some double values.
When these values are being set by the user, the value have to be checked to be inside some boundaries. When constructing an object the values have to be set to useful default values.
This is my example class:
classdef MyClass
properties ( Access = private )
Value = 0;
end
methods
function obj = MyClass( val )
obj = obj.set_value( val );
end
function obj = set_value( obj, val )
if val < 0
val = 0;
end
obj.Value = val;
end
function val = get_value( obj )
val = obj.Value;
end
end
end
The property is private with a valid default value and I have a setter with bound checking and a getter.
The constructor explicitly calls the setter.
The generated C++ code looks like this:
header:
class MyClass
{
public:
double get_value() const;
void init(double b_Value);
MyClass();
~MyClass();
private:
double Value;
};
source file:
double MyClass::get_value() const
{
return this->Value;
}
MyClass::MyClass() {}
MyClass::~MyClass() {}
void MyClass::init(double b_Value)
{
this->Value = b_Value;
}
The default value is lost, the setter does not even get defined, the bound checking is not happening.
Coder always generates an init method that sets the property directly.
How can I have the coder generate c++ code that does not allow the user of the class to misuse it?

回答 (1 件)

Darshan Ramakant Bhat
Darshan Ramakant Bhat 2021 年 3 月 4 日
Yes this is slightly tricky. The definition of the generated class is decided based on the actual use of that class in the other function (users of the class). In your example I am suspecting nobody is calling "set_value"so it will not get generated (since the codere decided that it is not required based on the usage. ). Unfortunately as of today you have no control over such class definitions.
I have used some tricks of MATLAB Coder and modified your code a bit. Using the below command I could generate class containing the required definition.
>> codegen -config:lib classWrapper -args {0} -lang:c++ -report
Please go through the attached code.
Hope this will be helpful for you.
  2 件のコメント
Darshan Ramakant Bhat
Darshan Ramakant Bhat 2021 年 3 月 4 日
In MATLAB Classes you can write custom setter / getter in the below manner :
These methods are supported for codegeneration as well. They should be called before setting or getting the values. I guess if you write your own setter and getters then it is not really guranteed to be called each time you set the values.

サインインしてコメントする。

製品


リリース

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by