op_prg_list_insert()
摘要
将指定的数据元素插入指定列表的指定位置。
注意: 该内核过程是一个仅为向后兼容而保留的宏调用。新代码应使用 prg_list_insert()。
语法
op_prg_list_insert (list_ptr, element_ptr, pos_index)
| 参数 | 类型 | 说明 |
|---|---|---|
list_ptr |
List* |
指向目标列表的指针 列表指针可以从多个内核过程获得:空列表可由 op_prg_list_create() 获得;表示文件内容的列表可由 op_prg_gdf_read() 获得;列表可由用户代码分配并通过 op_prg_list_init() 初始化。 |
element_ptr |
void* |
指向待插入元素的指针 任何数据类型都可以作为列表的元素,包括简单数据类型(如整数或字符串)和复杂数据结构。无需对元素指针进行类型转换。 |
pos_index |
int |
待插入元素在列表中的数字位置索引。[位置索引从表头的 0 开始,逐次加 1 直到表尾。既可以指定明确的数字位置索引,也可以使用符号常量(OPC_LISTPOS_HEAD 或 OPC_LISTPOS_TAIL。)] |
返回类型
void
无返回值。
示例
/* allocate a list */
list_ptr = (List *) op_prg_mem_alloc (sizeof (List));
/* initialize a list */
op_prg_list_init (list_ptr);
/** move the contents of subqueue #0 into the list **/
/* determine the number of packets in the subqueue */
subq_size = op_subq_stat (0, OPC_QSTAT_PKSIZE);
for (i = 0; i < subq_size; i++)
{
/* take a single packet from the subqueue head */
pkptr = op_subq_pk_remove (0, OPC_QPOS_HEAD);
/* insert the packet onto the list tail */
op_prg_list_insert (list_ptr, pkptr, OPC_LISTPOS_TAIL);
}
详情
元素可以按任意顺序插入列表,通过 pos_index 参数确定插入位置。当元素插入到列表表尾以外的位置时,插入点与表尾之间的元素的位置索引会依次上移一位。
可以使用特殊的符号列表位置 OPC_LISTPOS_HEAD 和 OPC_LISTPOS_TAIL 在列表的表头或表尾插入元素。建议尽可能使用这两个常量。
如果 pos_index 大于列表当前的元素数量,则该元素直接追加到列表末尾(不会插入额外的元素)。
该内核过程不会阻止向列表中重复插入元素。也就是说,同一元素地址允许出现在列表中的多个位置。
不要在列表中存储以临时变量表示的元素,因为变量内容会被覆盖。应当为每个元素显式分配内存,如下所示:
int* i_ptr; /* temporary variable */
i_ptr = (int *) op_prg_mem_alloc (sizeof (int));
*i_ptr = i; /* fill in desired contents of i_ptr */
op_prg_list_insert (list_ptr, i_ptr, pos_index);
注意: 该内核过程不是 MT 安全的,如 “Multi-Threading Safety“ 第 11 页所述。对共享列表的访问必须由外部串行化。
用途
提供一种向列表中插入元素的机制。列表通常用于存放文本信息(如路由表或地址转换表),或临时存放处理器中的一组数据包。
错误
- 程序中止:段错误。(由于列表指针非法或列表格式错误)
参考
- 使用内核过程 op_prg_list_remove() 从列表中移除元素
- 使用内核过程 op_prg_list_create() 让仿真内核分配一个新的空列表
- 使用内核过程 op_prg_list_init() 准备一个由用户代码分配的新空列表
- 使用内核过程 op_prg_list_free() 移除并释放列表上的所有元素(保留列表本身)