gpt4 book ai didi

arrays - Ada:用可变大小的数组打包记录

转载 作者:行者123 更新时间:2023-12-02 21:29:03 24 4
gpt4 key购买 nike

我希望创建一个打包记录,它可以容纳长度从 5 - 50 个元素不等的数组。是否可以以这样的方式来完成此操作,以便可以在不浪费空间的情况下打包记录?当我去创建记录时,我就会知道数组中有多少元素。

-- the range of the array
type Array_Range_T is Integer range 5 .. 50;

-- the array type
type Array_Type_T is array range (Array_Range_T) of Integer;

-- the record
type My_Record_T (Array_Length : Integer := 5) is
record
-- OTHER DATA HERE
The_Array : Array_Type_T(Array_Length);
end record;
-- Pack the record
for My_Record_T use
record
-- OTHER DATA
The_Array at 10 range 0 .. Array_Length * 16;
end record;

for My_Record_T'Size use 80 + (Array_Length * 16);

这显然不会编译,但显示了我正在尝试做的事情的精神。如果可能的话,我想将数组的长度保留在记录之外。

谢谢!

最佳答案

Ada 中确实没有办法按照您要求的方式表示记录。但是,由于您真正关心的不是记录在内存中的表示方式,而是如何将其传输到套接字,因此您可能不需要担心记录表示子句。

相反,您可以定义自己的 Write 例程:

procedure Write (Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Item : in My_Record_T);
for My_Record_T'Write use Write;

或者,我相信这将在 Ada 2012 中起作用:

type My_Record_T is record
...
end record
with Write => Write;

procedure Write (Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Item : in My_Record_T);

然后正文看起来像

procedure Write (Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Item : in My_Record_T) is
begin
-- Write out the record components, EXCEPT Array_Length and The_Array.
T1'Write (Stream, Item.F1); -- F1 is a record field, T1 is its type
T2'Write (Stream, Item.F2); -- F2 is a record field, T2 is its type
...

-- Now write the desired data
declare
Data_To_Write : Array_Type_T (1 .. Item.Array_Length)
renames Item.The_Array (1 .. Item.Array_Length);
-- I'm assuming the lower bound is 1, but if not, adjust your code
-- accordingly
begin
Array_Type_T'Write (Stream, Data_To_Write);
-- Note: using 'Write will write just the data, without any bound
-- information, which is what you want.
end;
end Write;

但是,如果需要打包其他组件,则此方法将不起作用。如果要向包含一个 3 位记录组件和一个 5 位记录组件的套接字写入一个字节。如果这是必要的,我认为内置的 'Write 属性不会为您做到这一点;您可能需要自己进行一些操作,或者您可能会变得棘手并定义一个 Stream_Elements 数组,并使用 Address 子句或方面来定义一个覆盖其余记录。但我不会使用覆盖方法,除非我 100% 确定套接字另一端的读取器是使用完全相同类型定义的 Ada 程序。

注意:我尚未对此进行测试。

关于arrays - Ada:用可变大小的数组打包记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22768834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com