How to get the class instance 'calling' path

조회 수: 3 (최근 30일)
Ludo Houben
Ludo Houben 2023년 10월 24일
답변: Ludo Houben 2023년 10월 26일
Hi all
I'm working on a class and I have added an error() message to a part of the code. However within my model several instances of the class will be available and I would like to know which instance is throwing the error. How can I find the instance 'calling' path (see red rectangle) within the class itself?

채택된 답변

Ludo Houben
Ludo Houben 2023년 10월 26일
The following 'works' when simulink is running in code generation execution when creating a class
% Create a property of the type string
properties (Nontunable)
sInstanceName string ='FB_TriggerBuffer';
end
% Create an 'InitFcn' callback function and update the property
set_param(gcb,'sInstanceName',gcb)
% The propery can now be used in the code
warning(sInstanceName);

추가 답변 (2개)

Pratyush
Pratyush 2023년 10월 25일
Hi Ludo,
I understand that you have added an error message in your class and you want to know which instance of the class has generated the error.
In MATLAB, you can use the "dbstack" function to obtain the call stack information, including the calling path within the class. You can refer to the following documentation for more information: https://in.mathworks.com/help/matlab/ref/dbstack.html
Here is an example how "dbstack" could be used to get the instance that throws the error:
classdef MyClass
properties
name
end
methods
function obj = MyClass(name)
obj.name = name;
end
function error(obj)
stack = dbstack();
calling_path = stack(1);
disp(['Error occurred in instance ''' obj.name ''' at line ' num2str(calling_path.line) ' in file ' calling_path.file]);
end
end
end
Hope this helps.
  댓글 수: 1
Ludo Houben
Ludo Houben 2023년 10월 25일
Hi Pratyush
Thank you for your solution. This works....however not completely. It works in 'Interpreted Execution', but not for 'Code Generation' simulation. Is there a solution for this?
Regards
Ludo

댓글을 달려면 로그인하십시오.


Ludo Houben
Ludo Houben 2023년 10월 26일
This is a simpeler solution if running simulink in interpreted execution
sInstancePath = gcb; % Get instance path
warning(sInstancePath); % Display warning with the path info

카테고리

Help CenterFile Exchange에서 Sources에 대해 자세히 알아보기

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by