Passing handle object to C++

Hi,
I've come across this issue while debugging a simple for-loop where the iteration time would grow overtime. The issue seems to stem from the fact that passing an handle object to a C++ MEX function extends the lifetime of the handle until the end of the script.
Here is a minimum example to reproduce the issue.
First, the class simply let us track when the object gets deleted:
classdef Foo < handle
methods
function this = Foo()
end
function delete(this)
disp("DELETE FOO");
end
end
end
Then, the C++-MEX function does nothing:
#include "mex.hpp"
#include "mexAdapter.hpp"
class MexFunction : public matlab::mex::Function
{
public:
void operator()(matlab::mex::ArgumentList /*outputs*/, matlab::mex::ArgumentList /*inputs*/) override
{
}
};
Compile this (work_with_Foo.cpp) with:
>>> mex work_with_Foo.cpp
Finally, the testing script:
index = 0;
while index ~= 3
v = Foo();
clear v;
index = index + 1;
end
disp("End of regular loop");
index = 0;
while index ~= 3
v = Foo();
work_with_Foo(v); % pass the handle to the C++ MEX function
clear v;
index = index + 1;
end
disp("End of work_with_Foo loop");
Which provides the output:
DELETE FOO
DELETE FOO
DELETE FOO
End of regular loop
End of work_with_Foo loop
DELETE FOO
DELETE FOO
DELETE FOO
Actually, if you insert more work after the second loop you can see that the handles are not deleted before the script ends.
Is this a known issue and is there any way to work around it?

2 Comments

I'm curious. Do you get the same behavior if Foo is not derived from handle?
There is no call to delete at all when Foo does not derive from handle so I can't really say out of the box.
If I add an onCleanup callback to Foo such as:
classdef Foo
properties (Hidden)
cleanup
end
methods
function this = Foo()
cleanup = onCleanup(@()delete(this));
end
function delete(this)
disp("DELETE FOO");
end
end
end
Then the output is what you would expect:
>> test_Foo
DELETE FOO
DELETE FOO
DELETE FOO
End of regular loop
DELETE FOO
DELETE FOO
DELETE FOO
End of work_with_Foo loop

Sign in to comment.

Answers (0)

Products

Release

R2018a

Asked:

on 30 May 2019

Commented:

on 31 May 2019

Community Treasure Hunt

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

Start Hunting!