我是一个C程序员,几周前开始学习Ada。我对Ada如何处理外来二进制数据感到困惑,例如在解码存储在串行输入缓冲区中的通信数据包时。
在C中,我将定义一个打包结构,以反映数据包的布局,然后将指针到缓冲区转换为指针到结构,以访问通信数据中的各个元素。在Ada中,典型的解码方式是什么?
我尝试用以下方法在Ada中复制C的相同方法
-- Fundamental types for fields in the packet
type Station_Addr_Type is mod 2**8;
type Func_Code_Type is (FUNC1, FUNC2);
for Func_Code_Type use
(
FUNC1 => 1,
FUNC2 => 2
);type Packet is
record
Station_Addr : Station_Addr_Type;
Func_Code : Func_Code_Type;
end record;
-- attempts to reflect packet binary layout
for Packet use
record at mod 1;
Station_Addr at 0 range 0 .. 7;
Func_Code at 1 range 0 .. 7;
end record;然后,我定义了通信接收缓冲区的数组,该缓冲区接受外来二进制数据(可能来自不同的体系结构):
type Communication_Data is mod 2**8;
for Communication_Data'Size use 8;
type Communication_Buffer is array (Natural range <>) of Communication_Data;
Buffer : Communication_Buffer (0 .. 20);然后是解码这类通信的过程
procedure Decode_Packet (Packet_Provided : in Packet);-- non-working sample
declare
begin
-- Attempts to sanity-check packet by object casting
Decode_Packet (Packet (Buffer));
---------------^----
Error: invalid conversion, not compatible with type "Communication_Buffer"
exception
when others =>
raise Decode_Failure;
end;但是,编译器禁止错误地进行这种转换,如图所示。谢谢你读了这么多。我的问题是,
关于外国二进制数据解码的正确方法,我是“在球场里”,还是有更好的方法去做?
发布于 2021-07-10 07:34:33
Buffer : Communication_Buffer (0 .. 20);
Pkg : Packet;
pragma Import (Ada, Pkg);
for Pkg'Address use Buffer (0)'Address;方面语法也是如此:
Buffer : Communication_Buffer (0 .. 20);
Pkg : Packet
with Import, Address => Buffer (0)'Address;subtype Packet_Buffer is Communication_Buffer (1 .. 2);
function To_Packet is new Ada.Unchecked_Conversion
(Packet_Buffer, Packet);
Pkg : Packet := To_Packet (Buffer (0 .. 1));PS。如果您想要一个独立的独立代码,您还可能需要一个订单 (GNAT实现定义的)方面。
PS。我还建议大家看看安全可靠的软件小册子中的“安全通信”一章。
https://stackoverflow.com/questions/68324778
复制相似问题