简体   繁体   English

如何在 omnet++ 中发送变量数据?

[英]How to send a variable data in the omnet++?

I´m trying to send a variable data in the omnet++, but it can only send a constant data.我正在尝试在 omnet++ 中发送变量数据,但它只能发送常量数据。

cMessage *msg=new cMessage(const char *s);

For example, how can I implement the following code?例如,如何实现以下代码?

data++;
cMessage *msg=new cMessage(""+data);
send(msg, "out");

Using the name of message to carry data is not a good idea.使用消息的名称来携带数据不是一个好主意。
The better way is to define own message with required fields.更好的方法是使用必填字段定义自己的消息 For example this way:例如这种方式:

  1. Create a new message file (for example DataMessage.msg ) with the content:创建一个包含以下内容的新消息文件(例如DataMessage.msg ):

     message DataMessage { int data; // here one can add other fields }
  2. Add in your C++ code:添加您的 C++ 代码:

     #include "DataMessage_m.h"
  3. To create, set the field and send a new message use this sample code:要创建、设置字段并发送新消息,请使用以下示例代码:

     DataMessage *msg = new DataMessage("DataMsg"); msg->setData(data); send(msg, "out");

Since data is an integer, all that is necessary is to convert it to a string.由于数据是 integer,因此只需将其转换为字符串。 The easiest way to do this in C++ is to use std::stringstream :在 C++ 中执行此操作的最简单方法是使用std::stringstream

std::stringstream ss;
ss << data;

Now ss.str().c_str() is of type const char * , which is accepted in cMessage 's constructor.现在ss.str().c_str()const char *类型,在cMessage的构造函数中被接受。

You just need to convert int type to string type and get C string from C++ string.您只需要将 int 类型转换为 string 类型并从 C++ 字符串中获取 C 字符串。

int data{};
cMessage *msg=new cMessage(std::to_string(data).c_str());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM