Skip to content

Commit c0bf923

Browse files
authored
Avoid dynamic allocation of message before sending over rosout (ros2#1067)
Signed-off-by: Christopher Wecht <[email protected]>
1 parent 627d7c6 commit c0bf923

File tree

1 file changed

+23
-19
lines changed

1 file changed

+23
-19
lines changed

rcl/src/rcl/logging_rosout.c

Lines changed: 23 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,14 @@ rcl_ret_t rcl_logging_rosout_fini_publisher_for_node(rcl_node_t * node)
325325
return status;
326326
}
327327

328+
static void shallow_assign(rosidl_runtime_c__String * target, const char * source)
329+
{
330+
target->data = (char *)source;
331+
size_t len = strlen(source);
332+
target->size = len;
333+
target->capacity = len + 1;
334+
}
335+
328336
void rcl_logging_rosout_output_handler(
329337
const rcutils_log_location_t * location,
330338
int severity,
@@ -356,25 +364,21 @@ void rcl_logging_rosout_output_handler(
356364
rcl_reset_error();
357365
RCUTILS_SAFE_FWRITE_TO_STDERR("\n");
358366
} else {
359-
rcl_interfaces__msg__Log * log_message = rcl_interfaces__msg__Log__create();
360-
if (NULL != log_message) {
361-
log_message->stamp.sec = (int32_t) RCL_NS_TO_S(timestamp);
362-
log_message->stamp.nanosec = (timestamp % RCL_S_TO_NS(1));
363-
log_message->level = severity;
364-
log_message->line = (int32_t) location->line_number;
365-
rosidl_runtime_c__String__assign(&log_message->name, name);
366-
rosidl_runtime_c__String__assign(&log_message->msg, msg_array.buffer);
367-
rosidl_runtime_c__String__assign(&log_message->file, location->file_name);
368-
rosidl_runtime_c__String__assign(&log_message->function, location->function_name);
369-
status = rcl_publish(&entry.publisher, log_message, NULL);
370-
if (RCL_RET_OK != status) {
371-
RCUTILS_SAFE_FWRITE_TO_STDERR("Failed to publish log message to rosout: ");
372-
RCUTILS_SAFE_FWRITE_TO_STDERR(rcl_get_error_string().str);
373-
rcl_reset_error();
374-
RCUTILS_SAFE_FWRITE_TO_STDERR("\n");
375-
}
376-
377-
rcl_interfaces__msg__Log__destroy(log_message);
367+
rcl_interfaces__msg__Log log_message;
368+
log_message.stamp.sec = (int32_t) RCL_NS_TO_S(timestamp);
369+
log_message.stamp.nanosec = (timestamp % RCL_S_TO_NS(1));
370+
log_message.level = severity;
371+
log_message.line = (int32_t) location->line_number;
372+
shallow_assign(&log_message.name, name);
373+
shallow_assign(&log_message.msg, msg_array.buffer);
374+
shallow_assign(&log_message.file, location->file_name);
375+
shallow_assign(&log_message.function, location->function_name);
376+
status = rcl_publish(&entry.publisher, &log_message, NULL);
377+
if (RCL_RET_OK != status) {
378+
RCUTILS_SAFE_FWRITE_TO_STDERR("Failed to publish log message to rosout: ");
379+
RCUTILS_SAFE_FWRITE_TO_STDERR(rcl_get_error_string().str);
380+
rcl_reset_error();
381+
RCUTILS_SAFE_FWRITE_TO_STDERR("\n");
378382
}
379383
}
380384

0 commit comments

Comments
 (0)