在 Ada 中为 reading/writing 映射共享内存块

Mapping chunk of shared memory for reading/writing in Ada

我有一个地址指向的两个进程之间的共享内存块(1024 字节)。我想将一些数据复制到这个共享内存,并在另一个进程上读取它。来自C背景,好像最简单的方法就是映射一条记录到这个地址,然后写入记录,但是好像没有正确复制。

目前,我正在尝试使用未经检查的转换将指针转换为指向记录的指针类型,并复制到记录中,但是当我将原始有效载荷与原始有效载荷进行比较时,我发现数据存在差异在第二个过程中收到。

这是正确的做法吗?:

type Payload_Array_Type is array (1..255) of Integer_32;

type Common_Buffer_Type is
  record
    Size : Integer_32;
    Payload : Payload_Array_Type;
  end record;

type Common_Buffer_Ptr_Type is access Common_Buffer_Type;

function Convert_Common_Memory_Ptr is new Unchecked_Conversion (
    Source => System.Address,
    Target => Common_Buffer_Ptr_Type);

Common_Memory_Ptr : System.Address;

procedure Copy_To_Common_Buffer
(
    Size : Integer_32;
    Payload : Payload_Array_Type
) is
    Common_Buffer_Ptr : Common_Buffer_Ptr_Type;
begin
    Common_Buffer_Ptr := Convert_Common_Memory_Ptr(Common_Memory_Ptr);
    Common_Buffer_Ptr.Size := Size;
    Common_Buffer_Ptr.Payload(1..255) := Payload(1..255);    
end Copy_To_Common_Buffer;

我会尝试这样做:

procedure Payload is 

   type Payload_Array_Type is array (1..255) of Integer_32;

   type Common_Buffer_Type is record
      Size : Integer_32;
      Payload : Payload_Array_Type;
   end record;
   for Common_Buffer_Type use record -- representation clause should be common to both processes
      Size    at 0 range 0 .. 31;
      Payload at 0 range 32 .. 1023;
   end record;
   for Common_Buffer_Type'Size use 1024; -- check this is also used in the other process.

   type Common_Buffer_Ptr_Type is access Common_Buffer_Type;

   Common_Memory_Ptr : System.Address; -- assuming this is where the shared object resides with a real address, possibly make it constant

   procedure Copy_To_Common_Buffer (Size    : in Integer_32;
                    Payload : in Payload_Array_Type) is
      Common_Buffer : Common_Buffer_Type;
      for Common_Buffer'Address use Common_Memory_Ptr; -- address overlay
   begin
      Common_Buffer := (Size => Size,
            Payload => Payload);
   end Copy_To_Common_Buffer;

begin

   Copy_To_Common_Buffer (9,(others => 876));

end Payload;

两个进程的类型定义应该是通用的,请注意我使用了表示子句来指定组件的去向。

我使用了地址覆盖来指定我正在写的位置,并且一次写完了整个记录。

还可以按照@Brian Drummond 的建议查看 pragma volatile 的用法。