Resolve Error: Passing by Reference Not Supported for Some Properties
Issue
When you generate C and C++ code from MATLAB® code, you can use the functions coder.ref, coder.wref, and coder.rref with coder.ceval to pass values by reference to an external C or C++
function. However, code generation does not support passing by reference for:
A property with a get method or a set method.
A property that has property validation.
A System object™ property with an attribute, such as
LogicalorPositiveInteger, that constrains or modifies the property value.
When you pass one these properties by reference, code generation fails with this error:
Code generation does not support
passing property 'myprop' to an external function by
reference because this property has an associated set method, get method, property
validation, or, for System object properties, an attribute that constrains or
modifies the property value.
Possible Solutions
To resolve this error, save the property value in a temporary variable. Then, pass the temporary variable by reference to the external function. After the external function call, assign the temporary variable to the property.
For example, consider the C function addone, which is declared in
the file addone.h and defined in the file
addone.c.
The MATLAB function useMySimpleClass_error class calls the C
function addone by using coder.ceval and passes
the input argument by reference to addone by using
coder.ref. The input argument to addone is a
property of the MATLAB class MySimpleClass. Code generation fails for
useMySimpleClass_error because the property
prop of the class MySimpleClass uses the
validation function mustBePositive.
function out = useMySimpleClass_error(x) %#codegen myObj = MySimpleClass; myObj.prop = x; if ~coder.target("MATLAB") coder.updateBuildInfo("addSourceFiles","addone.c"); coder.ceval("-headerfile","addone.h","addone",coder.ref(myObj.prop)); end out = myObj.prop; end classdef MySimpleClass properties prop {mustBePositive} end end
To resolve this error, assign myObj.prop to a temporary variable
and use the temporary variable in the coder.ceval call. After the
coder.ceval call, assign the temporary variable to
myObj.prop. For example, code generation for
useMySimpleClass
succeeds.
function out = useMySimpleClass(x) %#codegen myObj = MySimpleClass; myObj.prop = x; tempVar = myObj.prop; if ~coder.target("MATLAB") coder.updateBuildInfo("addSourceFiles","addone.c"); coder.ceval("-headerfile","addone.h","addone",coder.ref(tempVar)); end myObj.prop = tempVar; out = myObj.prop; end
See Also
codegen | coder.ceval | coder.ref | coder.rref | coder.target | coder.wref | coder.updateBuildInfo
