How to use c++ codegen to write to a ROS2 message, erroring at struct type

7 ビュー (過去 30 日間)
squared
squared 2025 年 4 月 23 日
コメント済み: squared 2025 年 4 月 24 日
I have the following code in maltab to be generated using codegen:
%change function to file name
function LidarObstacle()
%#codegen
pointnode_lane = ros2node("/ouster_driver_lane");
pubdistance_lane = ros2publisher(pointnode_lane,"/LaneDist","std_msgs/Float64MultiArray");
msg = ros2message(pubdistance_lane);
msg.data = coder.nullcopy(zeros(1, 20));
The error that is happening is:
Attempt to write a value of type 'std_msgs_Float64MultiArrayStruct_T' into a variable defined as type
'struct_T'. Code generation does not support changing types through assignment. To investigate the cause
of the type mismatch, check preceding assignments or input type specifications.
Is there a fix to this issue? I've tried multiple different ways. I've even tried Simulink at writing the

採用された回答

Prabeen Sahu
Prabeen Sahu 2025 年 4 月 24 日
Hi,
This is likely a limitation with your current version of MATLAB. When you create a ROS 2 message in MATLAB (e.g., std_msgs/Float64MultiArray), the message fields such as data are preallocated with a specific type and size. If you attempt to assign a whole new array (e.g., rmsg.data = zeros(1, 20)) or use coder.nullcopy, MATLAB Coder detects a type or size mismatch and produces an error.
Workaround:
Instead of coder.nullcopy(zeros(1, 20)), please use a loop to initialize msg.data as shown below:
function LidarObstacle()
%#codegen
pointnode_lane = ros2node("/ouster_driver_lane");
pubdistance_lane = ros2publisher(pointnode_lane,"/LaneDist","std_msgs/Float64MultiArray");
msg = ros2message(pubdistance_lane);
for ii = 1:20
msg.data(ii) = 0;
end

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeROS Network Access in Simulink についてさらに検索

製品


リリース

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by