共享代码的设计模式

共享代码项目的目标是维护一个代码仓库,同时为 Modeler 和真实平台编译并运行。根据你的需求,可能还有其它目标:多个真实平台、仿真器等。实现这一目标的方法有很多,下面两节介绍两种常用方法。

使用函数

在这种方法中,代码主体通过函数调用来处理平台相关的行为。你为每个平台实现一组函数,按需链接相应的那一组。

例如,你正在开发一个需要发送 hello 数据包的协议。你已经确定这涉及三个步骤,而这些步骤在 Riverbed 模型中和在真实硬件上必须区别处理。你的主代码可能如下所示(部分代码以注释形式抽象化):

double
calculate_next_tx_time (MyProtoState *state_ptr)
   {
   double curtime = platform_get_current_time ();
   // some complicated algorithm to determine when to send next, based on local state
   return complicated_val;
   }

void
send_hello_pkt (MyProtoState *state_ptr)
   {
   unsigned char pkt_data [500];
   // fill packet data with proper hello data
   platform_send_packet (state_ptr, pkt_data);
   double next_tx_time = calculate_next_tx_time ();
   platform_schedule_next_hello (state_ptr, next_tx_time);
   }

这三个平台相关的步骤由以下函数调用处理:

  • platform_get_current_time ()
  • platform_send_packet ()
  • platform_schedule_next_hello ()

每个函数都存在两个版本,一个用于模型代码,一个用于真实硬件。

使用 #ifdef

这种方法把所有代码放在同一个代码块中,利用编译器的 #ifdef 在编译时选择所需的代码。在某些情况下这比函数调用更简单,例如当程序逻辑必须随平台变化,或者你希望避免大量“空操作(no-op)”函数调用时。

下面的示例使用 OPD_DES 标识 Riverbed 专用代码。OPD_DES 符号在 Riverbed 代码中始终已定义。

#ifdef OPD_DES
void
blocking_udp_client_main (blocking_udp_clientT_Svars *svars, const char *init_str);
#else
int main (int argc, char *argv [])
#endif
   {
   char *my_init;
   #ifdef OPD_DES
   my_init = init_str;
   #else
   my_init = argv [1];
   #endif
   .
   .
   }

本站文档由 北京智网畅联科技有限公司 整理、翻译并提供 · Documentation compiled and provided by Beijing ZNetLink Technology Co., Ltd.

交流群 · QQ Group:OPNET/智网妙算网络仿真交流群(群号 486383494)

原文档 © 2017 Riverbed Technology · 本站为公益翻译,由 AI 辅助完成,请仔细甄别

Original documentation © 2017 Riverbed Technology. Community translation, AI-assisted. Contact: jiazequn@znetlink.com