Passing handle object to C++
Show older comments
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
James Tursa
on 30 May 2019
I'm curious. Do you get the same behavior if Foo is not derived from handle?
Pierre Gergondet
on 31 May 2019
Answers (0)
Categories
Find more on Use Prebuilt MATLAB Interface to C++ Library in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!