I'm trying to write a class that wraps around a serial
port to read a sensor:
classdef sensor < handle
properties
Value
s
end
methods
function obj = sensor(port)
obj.s = serial(port);
obj.s.BytesAvailableFcn = @(o,e) obj.getData;
fopen(obj.s);
end
function delete(obj)
disp('called destructor');
try
fclose(obj.s);
delete(obj.s);
end
end
function getData(obj)
obj.Value = fscanf(obj.s, '%d');
end
end
end
When I try to clear the workspace, the destructor never gets called:
>> foo = sensor('COM1');
>> clear foo % should disp() something!
Based on my previous experiences, there must still be a reference to foo
. Turns out this is embedded in the serial port foo.s
:
>> ports = instrfindall;
>> ports.BytesAvailableFcn
ans =
@(o,e)obj.getData
Once I clear out the BytesAvailableFcn
, i.e.,
>> ports.BytesAvailableFcn = '';
and then clear all
, I get my called destructor
displayed.
How can I break this circular reference and get my destructor to get called? If the destructor doesn't get called, the serial port stays bound.