主要内容

Resolve Error: Handle Object Referenced by Persistent Variable

Issue

If a persistent variable refers to a handle object, you can only instantiate the handle object once. If the code generator cannot determine that a function instantiates a handle object only once, code generation fails with this error:

Unable to reallocate a handle object referenced by a persistent variable because the handle object is created multiple times. For code generation, make sure that a handle object referenced by a persistent variable is created only once.

Possible Solutions

To ensure that a function instantiates a persistent variable only once, you must enclose the persistent variable assignment in an if statement with the isempty function. If you assign an instance of a handle class to a persistent variable, you must also enclose the statement that creates the handle class inside the if isempty statement.

For example, consider the handle class MyClass and the function usehandle_error. Code generation fails for usehandle_error because the function creates an instance of a handle class outside of the if isempty statement, and then assigns this instance to the persistent variable.

classdef MyClass < handle
   properties
       prop
   end
end
function out = useHandle_error(x)
persistent p;
myObj = MyClass;
myObj.prop = x;
if isempty(p)
    p = myObj;
end
out = p.prop;
end

To resolve this error, create the handle class instance and assign the handle class instance to the persistent variable inside the if isempty statement. For example, code generation succeeds for this function.

function out = useHandle_error(x)
persistent p;
if isempty(p)
    myObj = MyClass;
    p = myObj;
end
out = p.prop;
end

See Also

| |

Topics