You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将std::vector<Eigen::Vector2f>类型函数返回值转换为ROS话题消息发布

ROS Melodic路径消息类型转换方案

1. 核心问题定位

你当前的报错有两个根源:

  • 消息类型选择错误:geometry_msgs/Point仅支持存储单个三维坐标点,没有data字段,且无法承载路径所需的多组坐标序列
  • 类型不匹配:你的getPathFunction()返回的是多组二维坐标的集合,无法直接赋值给单个点消息的字段

2. 方案说明

ROS官方没有提供std::vector<Eigen::Vector2f>直接转路径消息的内置接口,但不需要引入第三方转换库,仅需少量自定义逻辑即可实现。
推荐使用官方标准路径消息nav_msgs/Path,该消息是ROS专为路径场景定义的通用格式,后续rviz可视化、导航栈对接都无需额外适配。

3. 完整代码实现

3.1 头文件引入

无需catkin环境,只要编译参数中配置好ROS头文件、Eigen头文件路径即可正常编译:

#include <ros/ros.h>
#include <nav_msgs/Path.h>
#include <geometry_msgs/PoseStamped.h>
#include <Eigen/Core>
// 替换为你自己的engine头文件
#include "your_engine_header.h"

3.2 主逻辑修改

int main(int argc, char** argv) {
    ros::init(argc, argv, "path_publisher");
    // 修复原代码拼写错误:NodeHangle -> NodeHandle
    ros::NodeHandle nh;
    // 替换消息类型为nav_msgs/Path
    ros::Publisher topic_pub = nh.advertise<nav_msgs::Path>("mytopic/path", 1000);
    ros::Rate rate(10);

    while (ros::ok()) {
        nav_msgs::Path path_msg;
        // 配置消息元信息,坐标系根据你实际场景修改
        path_msg.header.stamp = ros::Time::now();
        path_msg.header.frame_id = "map";

        // 拿到路径返回值
        std::vector<Eigen::Vector2f> path_points = engine.getPathFunction();
        path_msg.poses.resize(path_points.size());

        // 遍历转换每个坐标点
        for (size_t i = 0; i < path_points.size(); ++i) {
            path_msg.poses[i].header = path_msg.header;
            // 直接手动赋值坐标,无需引入额外转换依赖
            path_msg.poses[i].pose.position.x = path_points[i][0];
            path_msg.poses[i].pose.position.y = path_points[i][1];
            path_msg.poses[i].pose.position.z = 0.0;
            // 姿态字段无特殊需求填单位四元数即可
            path_msg.poses[i].pose.orientation.w = 1.0;
        }

        topic_pub.publish(path_msg);
        rate.sleep();
    }
    return 0;
}

4. 非catkin环境编译注意事项

编译时需要在你的编译参数中加入对应依赖的头文件和链接库,以g++为例:

  • 头文件路径:ROS安装路径下的include文件夹、Eigen头文件路径
  • 链接库:roscpp nav_msgs geometry_msgs

内容的提问来源于stack exchange,提问作者ferrrnum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 00:24:05