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 程序。
注意:我没有测试过这个。