【问题标题】:Adressing variables by variable names [duplicate]通过变量名寻址变量[重复]
【发布时间】:2021-02-05 10:34:50
【问题描述】:

我目前正在编写一个 ROS 2 节点来将值从 PLC 通过 ROS 传递到可视化:

PLC 系统 --> ROS --> 可视化

由于 ROS 应该只传递数据,所以我希望能够尽可能少地配置接口。这个想法可以用 ROS 最好地实现,它是一个配置文件(.msg 文件),其中输入了变量的名称及其类型。其他一切都由此衍生。 我不可避免地遇到了这个问题:在 ROS 中,数据是通过所谓的消息传递的。这些消息是通过结构定义的,并且是从我的配置文件中自动生成的。为了给结构体中的变量赋值,我不想处理程序中硬编码的每一个变量,而是使用已知名称遍历结构体。

TLNR:变量可以用变量名来寻址吗?

我知道整个事情听起来有点混乱。我希望下面的例子能阐明我的意思:

#include <vector>
#include <string>

struct MsgFile
{
    int someVariable;
    int someOtherVariable;
};

using namespace std;

class Example
{
public:
    vector<string> variableNames{"someVariable", "someOtherVariable"};
    MsgFile message;

    void WriteVariables()
    {
        for (auto const &varName : variableNames)
        {
            message."varName" = 0;  //<-- pseudo code of what I'm thinking of     
        }
    }
};

问候 蒂尔曼

【问题讨论】:

标签: c++ ros


【解决方案1】:

你不能使用这样的变量名。运行时没有变量名。如果您想要名称(字符串)和变量之间的映射,则需要自己添加。

如果您的“变量”属于同一类型,例如int,您可以使用映射:

#include <vector>
#include <string>
#include <unordered_map>    

using MsgFile = std::unordered_map<std::string,int>;


struct Example {
    std::vector<std::string> variableNames{"someVariable", "someOtherVariable"};
    MsgFile message;

    void WriteVariables() {
        for (auto const &varName : variableNames) {
            message[varName] = 0;  // add an entry { varName, 0 } to the map
                                   // (or updates then entry for key==varName when it already existed)
        }
    }
};

如果您只需要字符串表示来访问它(而不是用于打印等),您可以考虑使用枚举作为键。至少我会定义一些常量,比如const std::string some_variable{"some_variable"},以避免错别字被忽视(也许variableNames 应该是const(和static?))。

【讨论】:

  • 感谢您的回答。由于我最终被 ROS 绑定到 Struct,我想我将不得不对该部分进行硬编码。
  • @Tillman 你说它们是从配置文件生成的,你不能将它们生成为地图吗?在您的代码(和我的代码)中,名称和变量之间的映射在 Example 中完成,但也可以在 MsgFile 中完成
【解决方案2】:

据我所知,没有标准的方法可以做到这一点,我会选择另一种方式来存储数据(我的意思不是在 struct 中),但如果你坚持,这里有一个已回答的问题: Get list of C structure members

【讨论】:

  • 感谢您的回答。由于我最终被 ROS 绑定到 Struct,我想我将不得不对部分进行硬编码
猜你喜欢
  • 1970-01-01
  • 2011-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多