Using MATLAB Coder with a singleton class accessing Constant property returns error "Initial values of class types can only be used for reading properties"
10 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I am trying to use a singleton model for a class and would like to generate C code from some MATLAB code that uses this class. However, it seems to be returning the error "??? Initial values of class types can only be used for reading properties.". Below, I provide a small example demonstrating the issue. It is unclear what exactly the issue is given the error is occuring on the line trying to access the instance property (obj = SingletonClass.instance), and this line is reading a constant property of the class.
I have two questions:
- Could you help me understand the meaning of this error and why it is occuring?
- Is there a easy fix to this while still following the singleton model for the class?
Class definition:
classdef SingletonClass < handle
properties (Access = protected)
data (1,1) double = 5;
end
properties (Constant, Access = private)
instance (1,1) SingletonClass = SingletonClass();
end
methods (Access = private)
function this = SingletonClass()
% Constructor
end
end
methods (Static, Access = public)
function obj = Instance()
% Get singleton instance
obj = SingletonClass.instance;
end
end
methods (Access = public)
function out = test(this, val)
% Test code
out = this.data + val;
end
end
end
The function I am trying to use coder on:
function out = myfunction(val) %#codegen
obj = SingletonClass.Instance();
out = obj.test(val);
end
Codegen script:
val = double(0);
codegen myfunction -args {val}
2 Kommentare
Mukund Sankaran
am 27 Okt. 2022
Bearbeitet: Mukund Sankaran
am 27 Okt. 2022
For your second question, you could rewrite your static method to use persistent variables, like below, and that should work
classdef SingletonClass < handle
properties (Access = protected)
data (1,1) double = 5;
end
methods (Access = private)
function this = SingletonClass()
% Constructor
end
end
methods (Static, Access = public)
function obj = Instance()
% Get singleton instance
persistent instance
if isempty(instance)
instance = SingletonClass();
end
obj = instance;
end
end
methods (Access = public)
function out = test(this, val)
% Test code
out = this.data + val;
end
end
end
Mukund Sankaran
am 28 Okt. 2022
As regards your question #1, the error message is trying to say that you are only allowed to read the properties of "instance". For example, you are allowed to write an expression like this that reads the "data" property of "instance".
someVar = SingletonClass.instance.data + 1;
Antworten (0)
Siehe auch
Kategorien
Mehr zu MATLAB Classes finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!